Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setinterval function with arguments

Tags:

javascript

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

like image 453
user1871640 Avatar asked Mar 14 '13 13:03

user1871640


People also ask

How do you pass a function with arguments in setInterval?

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.

What are the parameters to be passed to setTimeout and setInterval?

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.

What is the minimum time we can give as a parameter to the setInterval method?

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.

How does a setInterval function return a value?

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


2 Answers

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.

like image 77
Manishearth Avatar answered Oct 12 '22 11:10

Manishearth


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.

like image 44
Esailija Avatar answered Oct 12 '22 11:10

Esailija