Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the remaining time of a setTimeout() [duplicate]

Tags:

javascript

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?

like image 739
Sam Avatar asked Sep 13 '10 12:09

Sam


People also ask

Does setTimeout repeat?

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.

How many times setTimeout executed?

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.

How do you wait for a setTimeout to finish?

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.

How long is setTimeout?

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.


2 Answers

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 );
}
  • This is custom sample code created "on the fly".
like image 101
Dubas Avatar answered Sep 29 '22 02:09

Dubas


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.

like image 43
Flynn1179 Avatar answered Sep 29 '22 02:09

Flynn1179