如何查找setTimeout()的剩余时间 [英] How to find the remaining time of a setTimeout()

查看:755
本文介绍了如何查找setTimeout()的剩余时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript:在setTimeout()中找到剩余时间?

我正在尝试使用 setTimeout()作为在JS中暂停一系列事件的方法。

这里是我正在做什么以及我想在评论中做些什么的例子 - http://jsfiddle.net / 8m5Ww / 2 /

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/

我可以用剩余的总毫秒数填充 var timeRemaining 的任何建议在 var a

Any suggestions how I can populate var timeRemaining with the total milliseconds remaining in var a?

推荐答案

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

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.

示例:

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 );
}




  • 这是创建的自定义示例代码飞。

  • 这篇关于如何查找setTimeout()的剩余时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆