0

I am new into JS , started few weeks ago. The issue I am having an issue with the Date.now() function.It's a very basic code , please go through it .

start = Date.now();
console.log(start);
setTimeout(count, 7000);

function count() {
  stop = Date.now();
  console.log(stop, start, stop - start);
}

And console output is

1600149626005 1600149618993 7012

Now, its clearly visible that its not equals to the delay that I have provided(7012!=7000).Moreover the result is different each and every time I run the code.Is this extra 12 ms, due to the code execution time or due to something else?

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 5
    Nothing is wrong with `Date.now()` - it gives you the correct time. `setTimeout` is not precise - it is a *minimum* delay before running the function but it might take a bit more (12ms is normal) depending on what else is running. – VLAZ Sep 15 '20 at 06:16
  • okay...understood. Thanks mate :) – Dip Chakraborty Sep 15 '20 at 06:20
  • I get 0 and 1 millisecond delays when I run that in Chrome's JavaScript console. – Ultimater Sep 15 '20 at 06:20
  • 1
    you should learn about the event loop, task que to understand why setTimeout has an delay – bill.gates Sep 15 '20 at 06:21
  • Before you downvote this question, consider that it has everything a question should have including working code, expectations and actual results. Nobody had to post any comments asking for clarification. Good question @DipChakraborty – Phil Sep 15 '20 at 06:23
  • 1
    @DipChakraborty that being said, next time make sure you search first – Phil Sep 15 '20 at 06:29
  • @Phil... Actually I was in a bit of rush, so I didn't search about this, thanks tho. – Dip Chakraborty Sep 23 '20 at 05:44

0 Answers0