How do I know how much time is left on an already set timeout descriptor?

timeoutHandle = setTimeout(function() { //code },1000); 

alert(timeoutHandle) returns me some strange numbers, like 1 or 2, should it look like 900 and count to 0 when the function is called? Therefore, I assume that I am doing it wrong.

+4
source share
2 answers

You can use Date.getTime() to get the representation of the Date object in milliseconds, so the (fairly accurate) approximation will be:

 timeoutHandle = setTimeout(function() { // code }, 1000); timeoutStart = new Date().getTime(); ... var elapsedTime = new Date().getTime() - timeoutStart; 

The return value of setTimeout and setInterval is just a kind of "timer identifier" - you use it to stop the timer with clearTimeout and clearInterval , it does not change dynamically.

Edit: As @Rocket points out, yes, you can use Date.now() instead of new Date().getTime() .

+4
source

You can not. Once the timeout is set, all you can do is undo it, clearTimeout . The number returned by setTimeout is just the handle that he used to cancel using clearTimeout .

+2
source

Source: https://habr.com/ru/post/1388761/


All Articles