1

Given a setInterval, can its timer keep getting quicker? Such as that the code to be ran starts at 2 seconds, then 1.9s, 1.8s, 1.7s, etc...? (at this point I'm not worried about reaching zero or negative.)

I currently have:

let speed = 2000;

let timer = setInterval(function() {
 display();
 faster();
 console.log(speed)
}, speed);

function faster() {
 speed -= 100;
}

function display(){
 // displays another square on canvas
}

I ask if it is possible because the console.log shows that the speed does indeed decrease, but the display function is not being called at faster intervals; it is always being called every 2 seconds. Therefor the speed of the setInterval is not getting faster....

Maxime Dore
  • 91
  • 1
  • 10
  • Have you tried using `setTimeout` instead of `setInterval` and call `timer` from inside the timer callback method? – Thijs Aug 28 '17 at 13:15
  • No, you can not change the interval timer of a running interval. You’d have to clear the current one and start a new one - or use setTimeout to begin with, if you want to execute it only once for any of those given time intervals. – CBroe Aug 28 '17 at 13:16
  • Already answered: https://stackoverflow.com/questions/28287914/how-to-change-the-speed-of-setinterval-in-real-time – Jorge Cabrera Aug 28 '17 at 13:17

1 Answers1

2

No. The setInterval() rate is fixed at the value of the second argument when the timer is started.

You can use setTimeout() instead, reestablishing the timer upon each invocation of the callback:

var rate = 100;
setTimeout(function callback() {
  // do something
  setTimeout(callback, rate - 10);
});
Pointy
  • 405,095
  • 59
  • 585
  • 614