Categories
JavaScript Answers

How to create an accurate timer in JavaScript?

Spread the love

Sometimes, we want to create an accurate timer in JavaScript.

In this article, we’ll look at how to create an accurate timer in JavaScript.

How to create an accurate timer in JavaScript?

To create an accurate timer in JavaScript, we should get the time from the Date object.

For instance, we write

setInterval(() => {
  console.log(new Date().toUTCString());
}, 1000);

to call setInterval with a callback that gets the latest datetime with the Date constructor.

And we call toUTCString to return a human readable datetime string.

1000 is the 2nd argument so the callback runs about every 1000 milliseconds.

Conclusion

To create an accurate timer in JavaScript, we should get the time from the Date object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *