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?)
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?)
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.
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.
Use this method:
var interval = setInterval( callback , 500 , arg1 , arg2[, argn ] );
[...]
function callback(arg1, arg2[, etc]){
}
More info here: window.setInterval
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
setInterval( function() { funca(10,3); }, 500 );