Possible Duplicate:
Javascript: find the time left in a setTimeout()?
I'm trying to use setTimeout()
as a way of pausing a series of events in JS.
Here's an example of what I'm doing and what I'd like to do in comments - http://jsfiddle.net/8m5Ww/2/
Any suggestions how I can populate var timeRemaining
with the total milliseconds remaining in var a
?
setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.
As specified in the HTML standard, browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times.
Use of setTimeout() function: In order to wait for a promise to finish before returning the variable, the function can be set with setTimeout(), so that the function waits for a few milliseconds. Use of async or await() function: This method can be used if the exact time required in setTimeout() cannot be specified.
Turns out the delay (in milliseconds) for these functions is a 32 bit signed quantity, which limits it to 231-1 ms (2147483647 ms) or 24.855 days.
You can't get directly the timer remaining seconds. You can save in a variable the timestamp when the timer is created and use it to calculate the time to the next execution.
Sample:
var startTimeMS = 0; // EPOCH Time of event count started
var timerId; // Current timer handler
var timerStep=5000; // Time beetwen calls
// This function starts the timer
function startTimer(){
startTimeMS = (new Date()).getTime();
timerId = setTimeout("eventRaised",timerStep);
}
// This function raises the event when the time has reached and
// Starts a new timer to execute the opeartio again in the defined time
function eventRaised(){
alert('WOP EVENT RAISED!');
clearTimer(timerId); // clear timer
startTimer(); // do again
}
// Gets the number of ms remaining to execute the eventRaised Function
function getRemainingTime(){
return timerStep - ( (new Date()).getTime() - startTimeMS );
}
Not possible, but if you set the contents of a separate var to the time you set it, you can easily figure it out manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With