如何使函数内部的变量值进行更新,对顶层变量起作用

时间:2022-05-16 16:55:16

Here the variable timer is declared outside timerIncrement function. Due to variable scope, I know changing the value inside the function wont change it outside. But I really need to come up something like this so that, once the idleTime > 5 it will use the new timer.

在这里,变量timer被声明为timerIncrement函数之外。由于变量作用域的不同,我知道改变函数内部的值不会改变函数外部的值。但是我真的需要做一些这样的事情,一旦空闲时间> 5它就会使用新的计时器。

How can I achieve this?

我怎样才能做到这一点呢?

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

    }

}

2 个解决方案

#1


1  

Since interval is set when initial call to setInterval made. modifying the value of delay will have no effect.

因为在对setInterval进行初始调用时设置了interval。修改延迟的值没有任何效果。

You should use setTimeout in this scenario.

您应该在此场景中使用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);
    }
});

#2


2  

This should work:

这应该工作:

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

    }

#1


1  

Since interval is set when initial call to setInterval made. modifying the value of delay will have no effect.

因为在对setInterval进行初始调用时设置了interval。修改延迟的值没有任何效果。

You should use setTimeout in this scenario.

您应该在此场景中使用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);
    }
});

#2


2  

This should work:

这应该工作:

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

    }