【问题标题】:How to find the remaining time of a setTimeout() [duplicate]如何找到 setTimeout() 的剩余时间 [重复]
【发布时间】:2011-04-11 15:23:48
【问题描述】:

可能重复:
Javascript: find the time left in a setTimeout()?

我正在尝试使用setTimeout() 作为在 JS 中暂停一系列事件的一种方式。
这是我正在做的以及我想在 cmets 中做的一个例子 - http://jsfiddle.net/8m5Ww/2/

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

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

    示例:

    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 );
    }
    
    • 这是“动态”创建的自定义示例代码。

    【讨论】:

    • 为什么我们不能在开发工具 goto 网络中使用 chrome 开发工具 -> XHR 你可以看到所有请求的大小和时间
    【解决方案2】:

    不可能,但是如果您将单独 var 的内容设置为您设置它的时间,您可以轻松地手动计算出来。

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2011-03-09
      • 2021-10-26
      • 1970-01-01
      • 2013-01-22
      • 2013-02-04
      • 1970-01-01
      • 2014-07-30
      • 1970-01-01
      相关资源
      最近更新 更多