【问题标题】:Resetting a setTimeout重置 setTimeout
【发布时间】:2009-09-24 16:12:11
【问题描述】:

我有以下:

window.setTimeout(function() {
    window.location.href = 'file.php';
}, 115000);

如何通过 .click 函数在倒计时中途重置计数器?

【问题讨论】:

  • 您可能可以使用现有的去抖动实现。

标签: javascript jquery


【解决方案1】:

您可以存储对该超时的引用,然后对该引用调用clearTimeout

// in the example above, assign the result
var timeoutHandle = window.setTimeout(...);

// in your click function, call clearTimeout
window.clearTimeout(timeoutHandle);

// then call setTimeout again to reset the timer
timeoutHandle = window.setTimeout(...);

【讨论】:

  • 太奇怪了,超时对象本身没有.clear()
  • @Cort3z 这是因为window.setTimeout 返回一个数字(计时器的 ID)而不是“超时对象”。
  • 是 @DanO :奇怪的是 setTimeout 没有返回 Timeout 对象。在 NodeJS 上下文中确实如此。
【解决方案2】:

clearTimeout() 并提供 setTimeout 的引用,这将是一个数字。然后重新调用它:

var initial;

function invocation() {
    alert('invoked')
    initial = window.setTimeout( 
    function() {
        document.body.style.backgroundColor = 'black'
    }, 5000);
}

invocation();

document.body.onclick = function() {
    alert('stopped')
    clearTimeout( initial )
    // re-invoke invocation()
}

在本例中,如果您在 5 秒内未点击 body 元素,则背景颜色将为黑色。

参考:

注意:setTimeout 和 clearTimeout 不是 ECMAScript 原生方法,而是全局窗口命名空间的 Javascript 方法。

【讨论】:

    【解决方案3】:

    您必须记住超时“计时器”,取消它,然后重新启动它:

    g_timer = null;
    
    $(document).ready(function() {
        startTimer();
    });
    
    function startTimer() {
        g_timer = window.setTimeout(function() {
            window.location.href = 'file.php';
        }, 115000);
    }
    
    function onClick() {
        clearTimeout(g_timer);
        startTimer();
    }
    

    【讨论】:

    • 有趣的是这个选项被忽略了。其他的似乎都需要把定时器内部的函数重复一遍,如果多几行代码要维护两次,也不会那么枯燥和痛苦……
    【解决方案4】:
    var myTimer = setTimeout(..., 115000);
    something.click(function () {
        clearTimeout(myTimer);
        myTimer = setTimeout(..., 115000);
    }); 
    

    类似的东西!

    【讨论】:

      【解决方案5】:

      对于 NodeJS,它超级简单:

      const timeout = setTimeout(...);
      
      timeout.refresh();
      

      来自文档:

      timeout.refresh()

      将计时器的开始时间设置为当前时间,并重新安排计时器以在之前指定的调整为当前时间的持续时间调用其回调。这对于在不分配新 JavaScript 对象的情况下刷新计时器很有用。

      但它在 JavaScript 中不起作用,因为在浏览器中 setTimeout() 返回一个数字,而不是一个对象。

      【讨论】:

        【解决方案6】:

        此计时器将在 30 秒后触发“Hello”警报框。但是,每次单击重置计时器按钮时,它都会清除 timerHandle,然后重新设置它。一旦它被触发,游戏就结束了。

        <script type="text/javascript">
            var timerHandle = setTimeout("alert('Hello')",3000);
            function resetTimer() {
                window.clearTimeout(timerHandle);
                timerHandle = setTimeout("alert('Hello')",3000);
            }
        </script>
        
        <body>
            <button onclick="resetTimer()">Reset Timer</button>
        </body>
        

        【讨论】:

          【解决方案7】:
          var redirectionDelay;
          function startRedirectionDelay(){
              redirectionDelay = setTimeout(redirect, 115000);
          }
          function resetRedirectionDelay(){
              clearTimeout(redirectionDelay);
          }
          
          function redirect(){
              location.href = 'file.php';
          }
          
          // in your click >> fire those
          resetRedirectionDelay();
          startRedirectionDelay();
          

          这里有一个详细的例子来说明真正发生的事情http://jsfiddle.net/ppjrnd2L/

          【讨论】:

            【解决方案8】:
            $(function() {
            
                (function(){
            
                    var pthis = this;
                    this.mseg = 115000;
                    this.href = 'file.php'
            
                    this.setTimer = function() { 
                        return (window.setTimeout( function() {window.location.href = this.href;}, this.mseg));
                    };
                    this.timer = pthis.setTimer();
            
                    this.clear = function(ref) { clearTimeout(ref.timer); ref.setTimer(); };
                    $(window.document).click( function(){pthis.clear.apply(pthis, [pthis])} );
            
                })();
            
            });
            

            【讨论】:

              【解决方案9】:

              要重置计时器,您需要设置并清除计时器变量

              $time_out_handle = 0;
              window.clearTimeout($time_out_handle);
              $time_out_handle = window.setTimeout( function(){---}, 60000 );
              

              【讨论】:

              • 啊,我建议不要在 javascript 中使用 php 样式的变量名。是的,它会起作用,但我的上帝,这令人困惑。
              【解决方案10】:

              我知道这是一个旧线程,但我今天想出了这个

              var timer       = []; //creates a empty array called timer to store timer instances
              var afterTimer = function(timerName, interval, callback){
                  window.clearTimeout(timer[timerName]); //clear the named timer if exists
                  timer[timerName] = window.setTimeout(function(){ //creates a new named timer 
                      callback(); //executes your callback code after timer finished
                  },interval); //sets the timer timer
              }
              

              然后你调用使用

              afterTimer('<timername>string', <interval in milliseconds>int, function(){
                 your code here
              });
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2011-11-03
                相关资源
                最近更新 更多