guagay_wk
guagay_wk

Reputation: 28088

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.

Upvotes: 23

Views: 31174

Answers (3)

alejandrociatti
alejandrociatti

Reputation: 1132

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

Upvotes: 48

xiaoboa
xiaoboa

Reputation: 1953

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

Upvotes: 31

mbonneau
mbonneau

Reputation: 617

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

Upvotes: 8

Related Questions