Changing a global variable inside a function, to change the setInterval's second parameter [duplicate]

佐手、 提交于 2019-12-13 03:27:18

问题


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


来源:https://stackoverflow.com/questions/57585017/changing-a-global-variable-inside-a-function-to-change-the-setintervals-second

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!