5

Here are some simple Javascript code using setTimeout:

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

When I run it on Chrome or Node.js, the results are similar:

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

You can see all tasks with timeout 0 and 1 are before timeout 2, which is what I expected.

But the 0 and 1 are mixed with each other, seems like they have the same timeout. What I expected is all 0 before 1.

How to understand this?

Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

0

Actually, setTimeout's second parameters has minimum value limitation. For firefox the value is 4ms. If the passed value is less than minimum value, minimum will be used.

Regarding your question, I think this article is helpful: http://javascript.info/tutorial/events-and-timing-depth

Ricky Jiao
  • 531
  • 4
  • 10