What is the difference between setTimeout(fn, 0) and setTimeout(fn, 1)?
setTimeout
has a minimum timeout of 4ms. So there is actually no difference between the two.
If the currently running task is a task that was created by the setTimeout() method, and timeout is less than 4, then increase timeout to 4.
Spec
EDIT: As pointed out by Ahmad in the comments, the spec has changed now, so the answer would currently be, "It depends."
I think the answer is "It depends" now.
We can run the code in different platform and browsers:
function setTimeouts() {
setTimeout(function() { console.log(2); }, 2);
setTimeout(function() { console.log(1); }, 1);
setTimeout(function() { console.log(0); }, 0);
}
for (var i = 0; i < 10; i++) {
setTimeouts();
}
For Node.js,
0
is converted to1
, so they are exactly the same: https://github.com/nodejs/node/blob/master/lib/timers.js#L319, and result might be:1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 2 2 2 2 2 2 2 2 2 2
For Chrome, the result is quite similar with Node.js
For Firefox, most of
0
will be printed before1
:0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2
I'm not sure the given answers are correct. Running the following code in Chrome, 0
is clearly invoking the bound function more quickly (just switch the timer values between 0
and 1
):
console.log("A");
console.log("B");
var start = new Date().getTime();
setTimeout(function() {
console.log(new Date().getTime() - start);
}, 0);
console.log("C");
console.log("D");
0
seems to be doing something like Node.js's setImmediate
, pushing an instruction onto the end of the current call stack, while 1
invokes whatever the implementation regards as a minimum value.