MortenMoulder
MortenMoulder

Reputation: 6646

How to stop loop with delay to continue another

I am trying to make two things happen at once, but only one of them is allowed. If something is already occuring, I need to be able to stop that completely and let the other one take over. Here is my example:

https://jsfiddle.net/mortenmoulder/5eceLvgu/

function log(text, interval, amount) {
    (function myLoop(i) {
        timer = setTimeout(function() {
            console.log(text);
            if (--i) myLoop(i);
        }, interval)
    })(amount);
}

$("#first").on("click", () => log("first", 500, 10));
$("#second").on("click", () => log("second", 500, 10));

Click on the first button, it will console.log("first") 10 times with a 500ms delay. When you click on the second button, it should cancel the first one and start console.log("second") without being interrupted (unless you click on the first button).

How can I do that? I need to delay the loop and I need to have one function to do this (so not a lot of if-statements with each button, as there are many buttons).

Upvotes: 0

Views: 76

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191749

You are already storing the timer, so you can clear its timeout.

https://jsfiddle.net/5eceLvgu/1/

var timer;
function log(...)
    clearTimeout(timer);
    (function myLoop(i) {

Upvotes: 0

t.niese
t.niese

Reputation: 40842

You need to store the timer id and clear it if you call log:

var logTimer;

function log(text, interval, amount) {
  clearTimeout(logTimer);
  (function myLoop(i) {
    logTimer = setTimeout(function() {
      console.log(text);
      if (--i) myLoop(i);
    }, interval)
  })(amount);
}

Upvotes: 2

Related Questions