112233
112233

Reputation: 2466

how to make variable value updated inside function to take effect on the top level variable

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.

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

    }

}

Upvotes: 1

Views: 37

Answers (2)

Satpal
Satpal

Reputation: 133403

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

You should use setTimeout in this scenario.

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

Upvotes: 1

Kamil Kamiński
Kamil Kamiński

Reputation: 156

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

    }

Upvotes: 2

Related Questions