cn0047
cn0047

Reputation: 17051

setTimeout works more that I expect

I have simple js script:

const printDate = (interval) => {
  setTimeout(() => {
    console.log(new Date());
    printDate();
  }, interval);
};
printDate(1000);

And I expect to see 1 record in console per 1 second because I'd passed 1000 as interval (which is 1 second).
But when I run this script I receive something like this:

km:gh kvol$ node test.js
2017-07-20T05:54:20.241Z
2017-07-20T05:54:20.244Z
2017-07-20T05:54:20.246Z
2017-07-20T05:54:20.247Z
2017-07-20T05:54:20.249Z
2017-07-20T05:54:20.250Z
2017-07-20T05:54:20.252Z
2017-07-20T05:54:20.253Z
2017-07-20T05:54:20.255Z
2017-07-20T05:54:20.256Z
2017-07-20T05:54:20.258Z
2017-07-20T05:54:20.259Z
2017-07-20T05:54:20.261Z
2017-07-20T05:54:20.262Z
2017-07-20T05:54:20.264Z
2017-07-20T05:54:20.265Z
2017-07-20T05:54:20.267Z
2017-07-20T05:54:20.268Z
2017-07-20T05:54:20.270Z
2017-07-20T05:54:20.271Z
2017-07-20T05:54:20.273Z
2017-07-20T05:54:20.274Z
2017-07-20T05:54:20.276Z
2017-07-20T05:54:20.277Z
2017-07-20T05:54:20.279Z
2017-07-20T05:54:20.280Z
2017-07-20T05:54:20.281Z
2017-07-20T05:54:20.283Z
2017-07-20T05:54:20.284Z
2017-07-20T05:54:20.286Z
2017-07-20T05:54:20.288Z
2017-07-20T05:54:20.290Z
2017-07-20T05:54:20.291Z
2017-07-20T05:54:20.293Z
2017-07-20T05:54:20.294Z
2017-07-20T05:54:20.296Z

Upvotes: 1

Views: 66

Answers (3)

Lukas Liesis
Lukas Liesis

Reputation: 26393

As Felix said, interval is undefined so only 1st timeout has 1000 value. If you don't define number for setTimeout it will use the minimum for the environment you run your code. It might be anything. Most likely between 3-10 ms. https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Notes

Visual:

enter image description here

Code:

const printDate = (interval) => {
  setTimeout(() => {
    console.log(new Date());
    printDate(interval);
  }, interval);
};
printDate(1000);

Upvotes: 1

Ragu
Ragu

Reputation: 51

You need to pass the interval to the printDate() function after printing the first date on console. The interval variable scope is available only on the first call, from the second call onwards the interval is not defined and it will simply print the date without delay.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816232

You are passing undefined as timeout in the recursive call: printDate(); (interval will be undefined), which is the same as passing 0.

If you want to use the same timeout, pass interval:

printDate(interval);

Upvotes: 5

Related Questions