Categories
JavaScript Answers

How to find the time left in a setTimeout() timer with JavaScript?

Spread the love

Sometimes, we want to find the time left in a setTimeout() timer with JavaScript.

In this article, we’ll look at how to find the time left in a setTimeout() timer with JavaScript.

How to find the time left in a setTimeout() timer with JavaScript?

To find the time left in a setTimeout() timer with JavaScript, we can use the timer’s _idleStart and _idleTimeout properties.

For instance, we write

const timeout = setTimeout(() => {}, 3600 * 1000);

const getTimeLeft = (timeout) => {
  return Math.ceil(
    (timeout._idleStart + timeout._idleTimeout - Date.now()) / 1000
  );
};

setInterval(() => {
  console.log("Time left: ", getTimeLeft(timeout), "s");
}, 2000);

to create the timeout timer object with setTimeout.

Then we calculate the time left before running the setTimeout callback with the getTimeLeft function.

In it, we use timeout._idleStart + timeout._idleTimeout - Date.now() to compute the time left before the setTimeout callback is run in milliseconds.

Then we divide the ceiling of the number and divide it by 1000 to get the number of seconds.

Next, we call setInterval with a callback that calls getTimeLeft with timeout in the callback to get the number of seconds left before the setTimeout callback is called every 2 seconds.

Conclusion

To find the time left in a setTimeout() timer with JavaScript, we can use the timer’s _idleStart and _idleTimeout properties.

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 *