From the setTimeout docs:
It is important to note that your callback will probably not be called in exactly delay milliseconds
The precision of the delay is determined by how little your code blocks, meaning that if you do a lot of operations on the single thread that your code has, the setTimeout
might be triggered with a lot of delay. On the opposite, it will be almost exact.
You could see the difference for yourself, execute this
var start = Date.now();
setTimeout(function() { console.log(Date.now() - start); }, 500);
for(var i=0; i<999999999; ++i){}
// 1237ms
and notice the difference with this:
var start = Date.now();
setTimeout(function() { console.log(Date.now() - start); }, 500);
// 507ms
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…