0

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()
frosty
  • 2,559
  • 8
  • 37
  • 73
  • You need to use `clearInterval` then initialize with `setInterval` again. Or you can use `setTimeout` instead. – Karan Aug 21 '19 at 05:36
  • You need to clear the lastIntervalId and start a new interval with desired values – Code Maniac Aug 21 '19 at 05:38
  • It clear now, the call to `setInterval()` creates a scheduled task **once**, that is executed continuously at the given interval. Your best bet is using `setTimeout()`. – Udo E. Aug 21 '19 at 06:54

2 Answers2

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);
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
  • Does it execute all the codes inside waitFunction first, before setting the timer to wait 5 seconds? Or does it do it at the same time? – frosty Aug 21 '19 at 05:55
  • @frosty No, the function is first called after 1 second and then recursively every 5 seconds. Feel free to run the code and see the console output! – frogatto Aug 21 '19 at 05:58
  • Right but if there's other code inside the waitFunction, for example, var number = 1; Does it set the number to 1 first, before waiting 5 seconds to run again? Or will it do it at the same time? – frosty Aug 21 '19 at 06:00
  • @frosty Yes, on every call, all statements run and then when everything is done, it schedules another call in 5 seconds. – frogatto Aug 21 '19 at 06:02
  • @frosty Please note that `setTimeout` is not a *blocking* function, it returns *immediately*. – frogatto Aug 21 '19 at 06:06
0

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);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320