How to run function with parameters using $timeout in AngularJS?

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.

$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);

Because the first parameter type of the $timeout is function, you need to do like this:

polling_interval=1000;
var poll = function(param1, param2) 
{
  //Execution code
  $timeout(function() {poll(param1, param2)}, polling_interval); 
}; 
poll(param1, param2);

Using an anonymous function would probably be the easiest way.

polling_interval=1000;
var poll = function(param1, param2) 
{
  //Execution code
  $timeout(function () { poll(param1, param2) }, polling_interval); 
}; 
poll(param1, param2);


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Adding open/closed icon to Twitter Bootstrap collapsibles (accordions)

Similar Posts