-1

This is my snippet of code for the setInterval:

  var t = 0;
  var speed = 1000;

// To display the speed
  setInterval(displaySpeed, 100);

  setInterval(timer, speed);

// To diplay the speed as well
function displaySpeed(){
  document.getElementById("Tem").textContent = speed;
}

function speedUp(){
  speed = speed - 100;
}

function slowDown(){
  speed = speed + 100;
 }

function timer(){
  t = Math.floor(Math.random() * 16) + 1;
  changeBackground();
}

The speedUp() and slowDown() are connected to a button with onclick. The buttons will change the variable, but not the actual speed. The timer function is to select a random number between 1 and 16.

  • 6
    To change the speed, you'll have to cancel the timer and set up a new one. –  Aug 19 '17 at 05:06

1 Answers1

1

EDIT: This code shows what /u/torazaburo answered in your question. Adds a sugar function to recreate the interval, and both methods speedUp() and slowDown() need to clear it in order to change the speed.

var intervalRef = setInterval(timer, speed);

function updateTimerSpeed(newSpeed) {
    intervalRef = setInterval(timer, newSpeed); 
}

function speedUp() {
  clearInterval(intervalRef);
  speed = speed - 100;
  updateTimerSpeed(speed);
}

function slowDown() {
  clearInterval(intervalRef);
  speed = speed + 100;
  updateTimerSpeed(speed);
}
  • Code without an explanation is not helpful. You should explain why the OP has their issue and how your code fixes it. – RobG Aug 19 '17 at 05:37
  • Edit, added attribution. I found [torazaburo](https://stackoverflow.com/users/663031/torazaburo) 's answer pretty concise and I didn't want to leech him/her off. – Mathias Rodriguez Aug 19 '17 at 06:09