0xAnon
0xAnon

Reputation: 897

Any way to stop previous async loop when clicking button again?

If I append a code of for loop in the browser DOM inside <script> tag by clicking on a button with i<50 and then instantly I appended another piece of code with i<2 by clicking on the Button again , so is there any way to stop the i<50 execution, is there any way I could stop the previous for loop execution?

I tried to solve it , but apparently i don't know enough and could not find any resource online.

First time click on button:

async function onGreenPlayButtonClicked() {
    for (var count = 0; count < 50; count++) {
        await new Promise(resolve => setTimeout(resolve, 1000)); // 1 SEC WAIT
        MinecraftAvatar.sayForNSeconds(greeting, 7)
    }
};

Second time click on button:

async function onGreenPlayButtonClicked() {
    for (var count = 0; count < 2; count++) {
        await new Promise(resolve => setTimeout(resolve, 10)); // 0.01 SEC WAIT
        MinecraftAvatar.sayForNSeconds(greeting, 7)
    }
};

I don't want FIRST loop still be executing when 2nd time button is clicked (when the first loop still executing, i modified code and clicked button again and updates script tag)

Upvotes: 0

Views: 1275

Answers (1)

Keith
Keith

Reputation: 24191

Ok, I'm back at PC now.

Below is a simple working snippet, I basically store a cancel function that gets stored, you can then check to see if it's been set on the green button click, if it is call it. All this cancel function does is set the local cancelMe flag to true, you can then use this in your for loop to abort..

ps. the greet var, is just there to show it's a new for loop, as I also reset this to 1 so that the count start from 1 again.

const delay = ms => 
  new Promise(resolve => setTimeout(resolve, ms));

let greet = 1; //just for debugging.

let cancel;

async function onGreenPlayButtonClicked() {
    if (cancel) cancel();
    let cancelMe = false;
    cancel = () => {
      cancelMe = true;
      greet = 1;
    }
    for (var count = 0; count < 50 && !cancelMe; count++) {
        await delay(1000);
        if (cancelMe) break; 
        console.log('greeting: ' + greet ++);
    }
};



document.querySelector('.green').
  addEventListener('click', onGreenPlayButtonClicked);
<button class="green">Green Button</button>

Upvotes: 2

Related Questions