19

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?

Community
  • 1
  • 1
Sam
  • 4,437
  • 11
  • 40
  • 59

2 Answers2

34

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".
Dubas
  • 2,855
  • 1
  • 25
  • 37
4

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.

Flynn1179
  • 11,925
  • 6
  • 38
  • 74