user2693017
user2693017

Reputation: 1860

What could be the reason for a javascript setTimeout taking multiple times as long to execute?

what could be the reason for a setTimeout to wait 2-4 times as long as configured to be executed?

  var TIMEOUT  = 700;

  console.log("TIMEOUT", TIMEOUT);

  var preTimeout = new Date();
  setTimeout(function() {
    console.log("timeout took:", new Date() - preTimeout);
  }, TIMEOUT);

This results in timeout took: from 1200-4000 on a website.

Upvotes: 0

Views: 912

Answers (1)

user234932
user234932

Reputation:

setTimeout() doesn't mean execute the code after exactly N milliseconds. It rather means, don't execute the code for at least N milliseconds.

The asynchronous code such as the setTimeout() callback is put on an event loop queue until all syncrhonous code finishes executing, and then it's run. This includes any async code that gets run in the queue before the timeout period. Your callback can run only after all those are done.

Here's a small demo to show this using synchronous while loop:

https://jsfiddle.net/foxbunny/1a9rckdq/

Code like the one in the demo is what you'll hear people referring to as 'blocking'. This is because it blocks the event loop queue.

I've also written a somewhat long article on the topic if you want a throrough overview.

Upvotes: 5

Related Questions