-2

i want to make this code work:

let wait = 1;

function speedup(){
  wait = 0.5
}

// I want it so that if the speed-up button is pressed the code repeats but faster
<html>
<body>
    <a onclick="speedup()">speed up</a>
    <p id="p">0</p>
</body>
</html>

Can anyone help? I need to use it for a game where the user can press a button to speed up a lengthy process for igc.

Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
  • "_button is pressed the code repaets but faster_" which **code** here are you referring to and how is it repeating right now? – palaѕн May 06 '20 at 07:58

1 Answers1

0

You can do something like:

let delay = 1000; // time in millisecond
let intervalId;

function speedUp() {
  delay = Math.max(0, delay - 100); // don't get negative time
  interval();
}

function interval() {
  // Clear existing interval
  if (intervalId) {
    clearInterval(intervalId);
  }

  intervalId = setInterval(() => {
    // run some code
  }, delay);
}

// Setup the first interval
interval();

// Call speedUp will cancel the previous setInterval, and start another one, 100msec faster
Kousha
  • 32,871
  • 51
  • 172
  • 296