Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval() behaviour with 0 milliseconds in JavaScript

In my application I found some JavaScript code that is using setInterval with 0 milliseconds, like so:

self.setInterval("myFunction()",0); 

Obviously, this does not seem like a good idea to me. Can anyone tell me what will be the behaviour of setInterval here? ("myFunction" makes an AJAX call to the server)

I am asking this because I am having an irregular behaviour in my application. 90% of the times, the application behaves correctly and exactly one call to the server is made. However sometimes, multiple calls are made to the server (until now, maximum is 48 calls) and I am almost certain it is the fault of this line of code.

like image 351
João Gomes Avatar asked Oct 04 '11 13:10

João Gomes


People also ask

How does the setInterval () function work in JavaScript O?

setInterval() The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval() .

How do I stop setInterval at 0?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

Does setInterval run immediately?

Method 1: Calling the function once before executing setInterval: The function can simply be invoked once before using the setInterval function. This will execute the function once immediately and then the setInterval() function can be set with the required callback.

How do you delay setInterval?

The setInterval method is used to schedule a function to be executed repeatedly after a period of time. The syntax for this method is this: const timerID = setInterval(function, delay, arg1, arg2, ...) In this case, the delay is the time in milliseconds that the timer should delay successive executions of the function.


1 Answers

Browser set a minimal value for the interval. Usualy 10ms, but it can depend on the browser. This means repeat this as fast as I'm possibly allowed. The W3C spec say 4ms : http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers

This is correct but probably reveal a design error.

EDIT: By the way, it is bad practice to pass a string to setTimeout/setInterval, pass a function instead as javascript has first class functions.

like image 81
deadalnix Avatar answered Sep 20 '22 23:09

deadalnix