I have this function inside my AngularJS controller. It looks like this;
polling_interval=1000; var poll = function() { //Execution code $timeout(poll, polling_interval); }; poll();
It uses the $timeout
service in AngularJS to keep calling itself. This works until I wanted to add parameters to this poll function. My code looks like this for the parameters added;
polling_interval=1000; var poll = function(param1, param2) { //Execution code $timeout(poll(param1, param2), polling_interval); }; poll(param1, param2);
The syntax was not acceptable and I am at a loss now. How do I execute the function with parameters using $timeout
in AngularJS? If this cannot be done, are there work-arounds to this problem? I would like to have my poll function accept parameters.
This '$timeout' service of AngularJS is functionally similar to the 'window. setTimeout' object of vanilla JavaScript. This service allows the developer to set some time delay before the execution of the function.
The $timeout service can be used to call another JavaScript function after a given time delay. The $timeout service only schedules a single call to the function. For repeated calling of a function, see $interval later in this text.
$timeout in AngularJs is similar to the window. setTimeout function in JavaScript. Usage of the $timeout service allows the developer to set some time delay to execute the methods and functions as per the requirement.
setTimeout in order to display an alert message after a timeout of at least 2000 milliseconds. Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $.
$timeout is Angular's wrapper for window.setTimeout. Naturally, just like setTimeout it supports passing additional parameters to the timed-out fn.
From AngularJS API:
$timeout([fn], [delay], [invokeApply], [Pass]);
[fn] (function) being your function
[delay] (number) the delay in ms
[invokeApply] (boolean) defaults to true, on true, the fn is run inside $apply, if false, it skips model dirty checking.
[Pass] additional parameters! This is what you want!
How your code should look like:
polling_interval = 1000; var poll = function(param1, param2){ //Execution code $timeout(poll, polling_interval, true, param1, param2); }; poll(param1, param2);
This is the proper way to pass parameters to a timed-out fn. I hope you find this useful.
EDIT: This feature was added on January 22, 2015 (v1.4.1), prior to that version, the correct approach would have been:
polling_interval = 1000; var poll = function(param1, param2){ //Execution code $timeout(poll.bind(null, param1, param2), polling_interval); }; poll(param1, param2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With