2

I am tring to build quiz app for my side project in vanila js and html. I have a a condition where i need to wait for sometime before executing a certain code.How can create function which take time as parameter to pause the code execution.

I tried solve the issue by creating a wait function as below but it didn't work as expected.

   const wait = (milliseconds) => {
        new Promise((resolve) => {
          setTimeout(() => {
            resolve();
          }, milliseconds);
        });
    };
    const execute = async () => {
        await wait(5000);
        console.log("Go To Next Question");
    };
    execute();

Rovan Lama
  • 33
  • 6
  • 1
    Either add `return` before `new Promise` or remove the curly brackets around the body of `wait`. Right now, it's not returning any value, so not waiting for the time you pass in. – VLAZ Nov 03 '22 at 07:37

1 Answers1

3

You are doing everything alright. You just missed return in the wait function you defined.

 const wait = (milliseconds) => {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve();
          }, milliseconds);
        });
    };
    const execute = async () => {
        await wait(5000);
        console.log("Go To Next Question");
    };
    execute();