如何查找setTimeout()的剩余时间

Sam*_*Sam 13 javascript

可能重复:
Javascript:在setTimeout()中找到剩余的时间?

我试图用setTimeout()它来暂停JS中的一系列事件.
以下是我正在做的事情以及我想在评论中做些什么的例子 - http://jsfiddle.net/8m5Ww/2/

有什么建议我可以填充var timeRemaining剩余的总毫秒var a

Dub*_*bas 25

您无法直接获得剩余秒数.您可以在创建计时器时将时间戳保存在变量中,并使用它来计算下次执行的时间.

样品:

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 );
}
Run Code Online (Sandbox Code Playgroud)
  • 这是"动态"创建的自定义示例代码.