Lecture
setImmediate(func)
method setImmediate(func)
The function deferred via setTimeout(..0)
will be executed no earlier than the next “tick” of the timer, the minimum frequency of which can be from 4 to 1000 ms. And, of course, this will happen after all current changes are redrawn.
But do we need this extra delay? As a rule, using setTimeout(func, 0)
, we want to postpone the execution of func
to “the nearest time after the current code”, and we don’t need any additional delay. If it were needed, we would specify it with the second argument instead of 0
.
setImmediate(func)
method setImmediate(func)
In order to put a function in a queue for execution without delay, Microsoft offered the setImmediate (func) method. It is implemented in IE10.
At setImmediate
only argument is a function whose execution needs to be scheduled.
In other browsers, setImmediate
does not exist, but it can be emulated using, for example, the postMessage method, designed to send messages from one window to another. Details of work with postMessage
can be found in the article Communicating windows from different domains: postMessage. It is advisable to read it after mastering the topic "Events".
Emulating setImmediate
with it for all browsers except IE <8 (which do not have postMessage
, so setTimeout will be used):
There are more complex emulations, including MessageChannel for working with Web Workers and a cunning method to support IE6-8: https://github.com/NobleJS/setImmediate. All of them are essentially hacks, aimed at providing support for setImmediate
in those browsers where there is none.
To compare the actual response frequency, let's measure the time for counting from 1 to 100 with setTimeout/setImmediate
:
Open in new window Open in sandbox
Run the example above - and you will see the real time difference between setTimeout(.., 0)
and setImmediate
. Yes, it can be more than 50, 100 or more times.
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone