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.
Related videos on Youtube
![Abishek Roka](https://lh6.googleusercontent.com/-LmPT3iH9rk4/AAAAAAAAAAI/AAAAAAAAEEo/tR0zOltvwQc/photo.jpg?sz=256)
Author by
Abishek Roka
Updated on October 26, 2020Comments
-
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 over 6 yearsHave 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 about 3 years@NewToJS is right! Also you can take a look to this similar question stackoverflow.com/questions/14226803/…
-
-
Shawn J. Molloy almost 6 yearsIts important to note this requires support for es6.