Implementing $timeout within ng-init to execute a function that showcases various shapes at 2-second intervals

I'm trying to use $timeout in Angular 1 to call a function every 2 seconds using ng-init.

ng-init="$timeout(sc.displaySorted(), 2000)"

The sc.displaySorted() function displays 100 sorted shapes on the DOM. It works fine with ng-init, but I'm struggling to get it to refresh every 2 seconds. I've also tried using $route.reload and recursion without success.

This is the vm.displaySorted function:

vm.displaySorted = function() {
// Call generateFunc and pass a total of 50 shapes
var allShapes = generateFunc(50);
// Call sortingFunc with all shapes as argument
var sortedShapes = sortingFunc(allShapes);
for(i = 0; i < sortedShapes.length; i++) {
  var shape = sortedShapes[i]
  if(shape.type === "square") {
    vm.shapesToDisplay.push(sortedShapes[i]);
  }
  if(shape.type === "circle") {
    vm.shapesToDisplay.push(sortedShapes[i]);
  }
}

//end vm.displaySorted

Answer №1

The solution you are seeking can be found in the $interval service. To use it, follow this example:

$interval(displaySorted, 2000)

Note the following:

  • You only need to include the function without calling it (without round brackets).

  • Avoid using

    ng-init="$interval(sc.displaySorted, 2000)"
    directly in your view as $interval is not accessible in the view but in the controller (a service provided by AngularJS). Therefore, create a function wrapper for the actual function. Refer to the complete sample code below.

angular
  .module('app', [])
  .controller('myctrl', function($interval) {
    var vm = this;
    vm.wizard = {
      displaySorted: fnDisplaySorted,
      init: fnInit
    }

    return vm.wizard;

    function fnInit() {
      $interval(fnDisplaySorted, 2000);
    }

    function fnDisplaySorted() {
      console.log('printing');
    }

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="myctrl as ctrl" ng-init="ctrl.init()">
</div>

Answer №2

Utilize the $interval feature to achieve this functionality. Make sure to add it in the controller as shown in the example below.

var app = angular.module('myApp', []);

app.controller('MyController', function MyController($scope, $interval) {
  this.displaySorted = function() {
    console.log("every 2 seconds");
  }
  this.runThis = function(){
    $interval(this.displaySorted, 2000);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController as sc' ng-app="myApp" ng-init="sc.runThis()">

</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions for setting a default value for ng-options when dealing with nested JSON data in AngularJS

I need help setting a default value for my ng-options using ng-init and ng-model with dependent dropdowns. Here is an example of my code: <select id="country" ng-model="statessource" ng-disabled="!type2" ng-options="country for (country, states) in c ...

Unlimited scrolling: Fetching additional data via an Ajax request?

I am working on setting up a table with infinite scroll functionality to showcase user information such as name, address, and email. To accomplish this, I began by importing the json-server package and creating an API endpoint using fakerjs in a separate f ...

Vue Bootstrap Checkbox and <b-table> with <b-form-checkbox> components combine to provide a powerful and flexible user

I am currently implementing b-form-checkbox with b-table to fetch the selected module Ids. <b-table id="module-table" :items="list.modules" :fields="fields" :busy="isBusy"> <template slo ...

What is the best method for interacting with multiple links in Puppeteer?

As a beginner with puppeteer, I am diving into the world of web scraping by attempting to create a simple scraping task. My Plan of Action The plan is straightforward: Visit a page, Extract all <li> links under a <ul> tag, Click on each < ...

What is the best way to make IE 10 display a pointer instead of an I-bar for a select list?

Is there a way to make IE 10 display a pointer instead of an I-bar when selecting from a list? Despite trying various methods found in similar questions, I have been unable to resolve this issue. The cursor: pointer property works as expected on other br ...

Having difficulty transforming the JSON data into the necessary format for Google Charts using JavaScript

The JSON data returned by the following controller is structured as shown below: [ {"classification":"CON","count":2}, {"classification":"PUB","count":1}, {"classification":"SENS","count":1} ] However, Google Charts requires the data to be in the followi ...

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

What could be causing the SyntaxError with JavascriptExecutor: Unexpected identifier?

Python PythonExecutor py = (PythonExecutor) driver; Boolean ready = (Boolean)py.executeScript("the following Python code"); Python Code var ready = False; window.onload = def check_ready(): ready = True def sleep(): return new Promise(resolve = ...

What is the best way to iterate through elements that come after a specific element?

I'm confident that I will be able to provide an answer to this very soon... Here's a sample code snippet: <script> function ClearAndRunFuncs(element) { //Clears responses for elements AFTER this element with an onchange //Executes the uni ...

What is the optimal method for verifying two distinct conditions simultaneously using Javascript?

Hey there, I'm working on a code snippet to check the status of a Rails model. Here's what I have so far: var intervalCall = setInterval(function(){ $.post("getstatus", {id:id}); var finished = "<%= @sentence.finished%>"; // CONDI ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

Guide to displaying a canvas as an image in a new tab using Reactjs

My current project involves using a canvas barcode generated by the react-barcode library. At the moment, I can only right-click on the canvas to open it as an image in a new tab. Is there a way to achieve this functionality with just a click of a button i ...

The dynamic ui-sref attribute in HTML fails to execute, while the href tag functions properly

Before moving to a controller, I make a web service call to GET a request. The response from this request is stored in the variable $rootScope.userSesion. I want this web service to run every time I switch to a different view without having to duplicate th ...

Having trouble accessing the data I'm setting in a separate component using the Context API

Currently working on my own project and I've encountered a problem while using the Context API. It's my first time using it. The issue I'm facing is that I can't seem to console.log the data I'm setting. I'm trying to create ...

Utilize the NPM Python Shell Callback Feature within Electron

I have a Python script that reads RFID tags when executed in the Python shell. Everything works fine with the script, but I'm facing an issue where I want to display "testing" using console.log() after the script is executed (when the tag is placed ov ...

When I attempt to press the shift + tab keys together, Shiftkey is activated

Shiftkey occurs when attempting to press the shift + tab keys simultaneously $("#buttonZZ").on("keydown",function (eve) { if (eve.keyCode == 9 && eve.shiftKey) { eve.preventDefault(); $("#cancelbtn").focus(); } if (eve. ...

A step-by-step guide to dynamically binding values to all browser tabs using localStorage and AngularJS

I currently have two files named index.html and server.js in my project. Within my code, I am utilizing local storage to retain text data across tabs. Below is the snippet of my implementation. I have two main queries: 1. Will the data persist when I clo ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Angular JS seems to be having some trouble with two-way binding

Here is the HTML code I am using: <div ng-controller="MainCtrl"> <tr data-ng-repeat="element in awesomeThings"> <div ng-if="$even"> <td ng-click="getServiceDetails(element)"> <a href="#"> ...

Discrepancy in div height between Chrome/Edge and Firefox browsers

I am currently in the process of designing a straightforward website layout that includes a navigation bar at the top. The main focus is on an image that needs to stretch from the bottom of the navbar to the bottom of the window, filling up the entire scre ...