[JavaScript] setTimeout(function(){}, 1) Can Sometimes Result in the Same Time Even When Specifying 1 Millisecond

Tadashi Shigeoka ·  Thu, October 26, 2017

I’ll share a troublesome situation where JavaScript’s setTimeout(function(){}, 1) sometimes results in the same time from Date.now() even when specifying 1 millisecond.

JavaScript

Testing Environment

In Node.js (v6.11.5 LTS) REPL, I executed the following three processes simultaneously to check if the Date.now() results would be exactly the same.

console.log(Date.now())
setTimeout(function(){
  console.log(Date.now());
}, 1)
''

The ” is executed so that the setTimeout object doesn’t display in the repl standard output.

setTimeout(function(){}, 1) Results in Same or Different Current Time

When Date.now() Results Were the Same Time

> console.log(Date.now()), setTimeout(function(){ console.log(Date.now()); }, 1), ''
1509078324903
''
> 1509078324903

When Date.now() Results Were Different Times

> console.log(Date.now()), setTimeout(function(){ console.log(Date.now()); }, 1), ''
1509078326782
''
> 1509078326784

That’s all from the JavaScript Gemba, where I got stuck with setTimeout(function(){}, 1) giving the same time.