Javascript How do I wait x seconds before running next line of code?

28,436

Solution 1

Can now nicely be done with promises:

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

async function demo() {
  console.log('Taking a break...');
  await sleep(2000);
  console.log('Two second later');
}

demo();

Solution 2

Please try using the setTimeout function:

setTimeout(function(){ alert("Hello"); }, 3000);

From this link:

https://www.w3schools.com/jsref/met_win_settimeout.asp

So for your specific use case:

var timeToWait = 3000; // in miliseconds.
function testFunction() {
    alert("Test");
 }

 if (x > y) {
      setTimeout(function(){ testFunction(); }, timeToWait);
  }

Hope that helps.

Share:
28,436

Related videos on Youtube

Abishek Roka
Author by

Abishek Roka

Updated on October 26, 2020

Comments

  • Abishek Roka
    Abishek Roka over 3 years

    I would like to be able to make something similar to this:

    function testFunction() {
        alert("Test");
    }
    
    if (x > y) {
        wait(z);
        testFunction();
    }
    

    Thanks!

    • NewToJS
      NewToJS over 6 years
      Have you tried placing the part of source code into a setTimeout? setTimeout(function(){ //this will run after 3 seconds}, 3000); If you could be more clear with your question and say which section you want to wait or why it might be easier for someone to give you a solid answer.
    • lmoglia
      lmoglia about 3 years
      @NewToJS is right! Also you can take a look to this similar question stackoverflow.com/questions/14226803/…
  • Shawn J. Molloy
    Shawn J. Molloy almost 6 years
    Its important to note this requires support for es6.