-->

Changing a global variable inside a function, to c

2019-08-28 02:55发布

问题:

This question already has an answer here:

  • Changing the interval of SetInterval while it's running 14 answers

I have a global variable called interval, and I need to change this global variable to 5000 inside a function, so after waiting for 1 second, the setInterval function will now wait for 5 seconds. However, when I tried the code below, it only waits 1 second every time it's executed.

var timeToWait1 = 1000;
var timeToWait2 = 5000;
var interval = timeToWait1;

setInterval(function(){ waitFunction () }, interval);

function waitFunction() {
interval = timeToWait2;
} //end of function waitFunction()

回答1:

Interval is set once and can't be changed, You'd need timeout.

var timeToWait1 = 1000;
var timeToWait2 = 5000;

setTimeout(waitFunction, timeToWait1);

function waitFunction() {
  console.log('waitFunction called');
  setTimeout(waitFunction, timeToWait2);
}



回答2:

Once an interval has started, you can't change the duration it uses. You'll have to stop the interval and re-start it with the new duration.

let intervalId;
let makeInterval = duration => {
  console.log('making a new interval');
  intervalId = setInterval(waitFunction, duration);
};

makeInterval(1000);

function waitFunction() {
  clearInterval(intervalId);
  console.log('waitFunction running');
  makeInterval(5000);
}

You might consider using a recursive setTimeout instead, to avoid the need for clearing:

let makeTimeout = duration => {
  console.log('making a new timeout');
  setTimeout(waitFunction, duration);
};

makeTimeout(1000);

function waitFunction() {
  console.log('waitFunction running');
  makeTimeout(5000);
}