This is usually used so that errors or long loops within callback
do not affect what comes after setTimeout
, it is an "simulate" the Multiple threads
( multithread ), is not a thread
true, but works on the same line.
With 0
(zero), it will run at the same time that setTimeout
is called, but it will not be necessary what comes after setTimeout
wait for the process to finish, it is as if the callback were executed in a separate "process"
For example:
function meuCallback() {
console.log("Level2");
}
console.log("Level1");
setTimeout(meuCallback, 0);
console.log("Level1");
In the example it will deliver something like:
Level1
Level2
Level1
But it's worth noting that every engine (ECMAScript browser technology - popularly called Javascript) adjusts as needed and tries its way to get better performance, sometimes the same script can deliver something like:
Level1
Level1
Level2
An example that some people use to avoid errors would be something like:
function meuCallbackComError() {
(a + b);
}
console.log("Execução 1: Level1");
setTimeout(meuCallbackComError, 0);
console.log("Execução 2: Level1");
See that in the log something like:
Execution 1: Level1
Execution 2: Level1
Uncaught ReferenceError: a is not defined
In other words, the second console.log
was not affected by the error.
Why not use zero in setTimeout
Does not mean that you will never use, for example just to avoid errors that can be caused within the callback zero will be enough, the situations that we should avoid 0
is when there are processes of the browser itself that can delay, such as rendering images after onload
, we often use setTimeout
to wait for another process to finish, for example an image inserted by javascript, even using Image.onload
yet it did not render within a millionth of second (something imperceptible to human being), then a little delay can help, like:
-
setTimeout(..., 1)
- works for most rendering cases this can work
-
setTimeout(..., 10)
- this may be preferable to others and hardly a human will notice
-
setTimeout(..., 100)
- in some cases we need a longer delay, where there is an element that will take a while to render (hardly a human will see this).
Alternatives to setTimeout
It works fine in most cases, but it should be noted that scripts that are slow to execute will still freeze the webbrowser for some time (depending on the script), even using setTimeout
.
I recommend you read this other answer, it explains the callbacks and setTimeout
:
There are currently more functional solutions to avoid freezing, for example:
However if you just want to prevent small delays or errors that may occur, then use only setTimeout
if you want to run scripts that take more than 500ms to process then Web Workers or the AMD may be useful to you.
Note that AMD is being used by many libraries, such as jQuery for example. See a snippet of jQuery :
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}