Home > Software design >  How can I quit from a javascript function with a bunch of awaits when certain condition is met
How can I quit from a javascript function with a bunch of awaits when certain condition is met

Time:08-20

I have a website with some animations when it starts, and I want to add a skip-animation button. Currently the animation is a function with lots of awaits, so how can I quit from this process when the skip-animation button is clicked? Indeed I can just add if (condition === true) {return;} between every line, but are there some easier ways of doing this?

For example, how can I immediately quit from this animation function when the skip-animation button is clicked?

var skip-animation = document.querySelector("#skip-animation);

function animation() {
  await function1();
  await function2();
  function3();
  await function4();
  function5();
}

CodePudding user response:

One solution I can think of, would be to put all your functions into an array. Then, you loop through the array and run each function while checking the condition.

const functions = [f1, f2, f3, f4, f5];
for (function of functions) {
  if (buttonNotClicked) {
    await function();
  }
}

Unfortunately this will not immediately quit the function like you wanted and as stated by @JaromandaX that may be difficult or even impossible without modifying the animation functions themselves.

CodePudding user response:

This is one way I thought myself. I add a check before every functions, which throws an exception if the condition is met. and add a try catch in the animation function, which handles the exception. In this case, it will stop the process after skip === true, but it's also not "immediate" as I expected

skip-animation.onclick = () => {
  skip = true;
}

function func1() {
  if (skip === true) {
    throws new error("SKIP IT");
  }
}

function animation {
  try {
    await func1();
    await func2();
    func3();
  }
  catch(e) {
    if (e.message === "SKIP IT") {
      doSomething();
    } else {
      throw e;
    }
  }
}

  • Related