【问题标题】:how to make variable value updated inside function to take effect on the top level variable如何在函数内部更新变量值以对顶级变量生效
【发布时间】:2016-08-11 10:38:08
【问题描述】:

这里的变量 timer 是在 timerIncrement 函数之外声明的。由于范围可变,我知道在函数内部更改值不会在外部更改它。但我真的需要想出这样的东西,这样,一旦idleTime > 5 它将使用新的计时器。

我怎样才能做到这一点?

jQuery(document).ready(function($) {

   var timer = 1000;
  //   //increment the idle time counter every sec.
  var idleInterval = setInterval(timerIncrement, timer); // 1 sec


    function timerIncrement() {
      while(idleTime < 5){
        console.log('test '+idleTime);
        idleTime = idleTime + 1;
         }  
         timer = 2000;//how to make this take affect on the top so that setInterval run at this newly set timer
         console.log('reached max');

    }

}

【问题讨论】:

    标签: jquery scope


    【解决方案1】:

    这应该可行:

    function timerIncrement() {
          while(idleTime < 5){
            console.log('test '+idleTime);
            idleTime = idleTime + 1;
             }  
             timer = 2000;//how to make this take affect on the top so that setInterval run at this newly set timer
             clearInterval(idleInterval); 
             idleInterval = setInterval(timerIncrement, timer);
             console.log('reached max');
    
        }
    

    【讨论】:

      【解决方案2】:

      因为在首次调用setInterval 时设置了间隔。修改delay的值是没有效果的。

      在这种情况下,您应该使用setTimeout

      $(document).ready(function() {
          var timer = 1000;
          var idleInterval = setTimeout(timerIncrement, timer); // 1 sec
      
          function timerIncrement() {
              timer = 2000
              //Recursively call your method
              idleInterval = setTimeout(timerIncrement, timer);
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2022-11-21
        • 2021-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-02
        • 1970-01-01
        • 2019-08-22
        • 1970-01-01
        相关资源
        最近更新 更多