0

Currently the JavaScript runs perfectly fine on one click. However, when I click the "Test Test" button while the function is already running, it will seemingly interrupt itself. I want the second click to queue itself up and wait until the "Thank you!" goes away. After the "Thank you!" from the first click goes away, then, and only then, I want the second click to run the function again.

This should be for all subsequent clicks. If I click the button 5 times in a row very quickly, the full function should play through 5 times, in order, as opposed to overlapping itself and only typing one "Thank you".

Here is the JS in demo form: https://jsfiddle.net/p562thwe/

let egg = document.querySelector("#egg");
let petEffects = document.querySelector("#streamPet");

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

document.querySelector("#button").onclick = async function demo() {
    egg.classList.add("bounce");
  await sleep(3000);
    egg.classList.remove("bounce");
    petEffects.innerText = `Wowee!`;
    petEffects.classList.add("typing");
  await sleep(2000);
    petEffects.innerText = ``;
    petEffects.classList.remove("typing");
  await sleep(100);
    petEffects.innerText = `Thank you!`;
    petEffects.classList.add("typing");
  await sleep(3000);
    petEffects.innerText = ``;
    petEffects.classList.remove("typing");
}

demo();

I have tried adding a boolean, but I couldn't get it working, nor do I think it would 'queue' up the next instances.

Justin
  • 15
  • 3

1 Answers1

0

You can build exactly that: a queue.

const queue = [];
let running = false;

function run() {
  if (queue.length > 0) {
    running = true;
    const next = queue.shift();
    next().then(run); // this will call run again when the promise is "done"
  } else {
    running = false;
  }
}

async function demo() {
  ...
}

document.querySelector("#button").onclick = function() {
  queue.push(demo);
  if (!running) {
    run();
  }
};
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • That's actually very cool, I've never seen a queue system built out. However, I'm not sure where to insert the rest of my code here. I tried to add it under run(); but I feel like I'm doing something wrong. I will continue experimenting, but would love a nudge in the right direction. I had also added the code above and below with different results, neither of which were good. – Justin Dec 22 '20 at 21:14
  • Just define your function somewhere. I updated the example. – Felix Kling Dec 23 '20 at 08:42
  • Thank you, but I had already tried that. https://jsfiddle.net/p562thwe/2/ I feel like I'm missing something very obvious, sorry! – Justin Dec 23 '20 at 12:15
  • Oh, I got it working! 99% anyway. Thank you so much. I accepted your answer. – Justin Dec 23 '20 at 15:08