Javascript 如何找到 setTimeout() 的剩余时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3700200/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the remaining time of a setTimeout()
提问by Sam
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/
我正在尝试setTimeout()用作一种在 JS 中暂停一系列事件的方式。
这是我正在做什么以及我想在评论中做什么的示例 - http://jsfiddle.net/8m5Ww/2/
Any suggestions how I can populate var timeRemainingwith the total milliseconds remaining in var a?
任何建议如何填充var timeRemaining剩余的总毫秒数var a?
回答by Dubas
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".
- 这是“即时”创建的自定义示例代码。
回答by Flynn1179
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.
不可能,但是如果您将单独 var 的内容设置为您设置它的时间,您可以轻松地手动计算出来。

