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?)
The setInterval() method can pass additional parameters to the function, as shown in the example below. setInterval(function, milliseconds, parameter1, parameter2, parameter3); The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
The first parameter is required and is the callback function to be executed. The second parameter is optional and represents the number of milliseconds to wait before invoking the callback function.
To mitigate the potential impact this can have on performance, once intervals are nested beyond five levels deep, the browser will automatically enforce a 4 ms minimum value for the interval. Attempts to specify a value less than 4 ms in deeply-nested calls to setInterval() will be pinned to 4 ms.
function git(limit) { var i = 0; var git = setInterval(function () { console. log(i); if (i === limit - 1) { clearInterval(git); return 'done'; } i++; }, 800); } var x = git(5); console. log(x);
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.
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