Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading