17

How do I pass arguments in the setInterval function Eg:

 intId = setInterval(waiting(argument), 10000);

It shows error : useless setInterval call (missing quotes around argument?)

user1871640
  • 441
  • 2
  • 8
  • 18
  • 1
    setInterval(function(){waiting(argument)}, 10000) – rab Mar 14 '13 at 13:19
  • possible duplicate of [Pass parameters in setInterval function](http://stackoverflow.com/questions/457826/pass-parameters-in-setinterval-function) – 416E64726577 Apr 08 '14 at 21:29

5 Answers5

47

Use an anonymous function

 intId = setInterval(function(){waiting(argument)}, 10000);

This creates a parameterless anonymous function which calls waiting() with arguments

Or use the optional parameters of the setInterval() function:

 intId = setInterval(waiting, 10000, argument [,...more arguments]);

Your code ( intId = setInterval(waiting(argument), 10000);) calls waiting() with argument, takes the return value, tries to treat it as a function, and sets the interval for that return value. Unless waiting() is a function which returns another function, this will fail, as you can only treat functions as functions. Numbers/strings/objects can't be typecast to a function.

Manishearth
  • 14,882
  • 8
  • 59
  • 76
10

You can use Function#bind:

intId = setInterval(waiting.bind(window, argument), 10000);

It returns a function that will call the target function with the given context (window) and any optional arguments.

Esailija
  • 138,174
  • 23
  • 272
  • 326
7

Use this method:

 var interval = setInterval( callback , 500 , arg1 , arg2[, argn ] );
 [...]
 function callback(arg1, arg2[, etc]){
 }

More info here: window.setInterval

alexbusu
  • 701
  • 4
  • 13
1

You can use the bind and apply functions to store the argument in state.

Example using bind in node shell:

> var f = function(arg) { console.log (arg);}
> f()
undefined
> f("yo")
yo
> var newarg = "stuff";
> f(newarg)
stuff
> var fn = f.bind(this, newarg);
> fn()
stuff
> var temp = setTimeout(fn,1000)
> stuff
Rondo
  • 3,458
  • 28
  • 26
-3

setInterval( function() { funca(10,3); }, 500 );

AHmedRef
  • 2,555
  • 12
  • 43
  • 75