Search code examples
javascriptecmascript-6promisefunction-call

Wait/pause code execution for given amount of time before executing certain function in JavaScript


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();


Solution

  • 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();