How to wait for a period of time after a function run
Just put your code inside an anonymous function passed to setTimeout.
e.g.
functionToRunFirst();
setTimeout(function() {
// rest of code here
}, 2000);
I think what you're looking for is a method to suspend the execution of the code until a timeout. Many amateur programmers wish for such a construct, but it doesn't exist in JavaScript. It's not needed. For all purposes in JavaScript setTimeout
and setInterval
are perfect candidate solutions.
However, JavaScript is a powerful language. You can build your own construct to address this issue. Take a look at Neil Mix's blog post. With his approach you can create a sleep function which can be used along the following lines (note that currently only Firefox supports JavaScript 1.7):
function mainGeneratorFunction() {
functionToRunFirst();
yield sleep(2000);
//rest of the code
}
However, for other browsers don't despair. You can use a hack known as XHR Sleeping
. In this approach you simply use a synchronous XMLHttpRequest
to call a server side script like php, which then sleeps for the specified time and returns after it wakes up. The JavaScript code is as follows:
function sleep(microseconds) {
var request = new XMLHttpRequest();
request.open("GET", "sleep.php?time=" + microseconds, false);
request.send();
}
functionToRunFirst();
sleep(2000000);
//rest of the code
The php sleep function is as follows:
<?php
usleep($_GET["time"]);
?>
using setTimeout
is one way to do it
function run() {
// run this code
setTimeout(afterTwoSeconds, 2000);
}
function afterTwoSeconds() {
// run this code two seconds after executing run.
}
// call run
run();