Execute script after specific delay using JavaScript
Just to expand a little... You can execute code directly in the setTimeout
call, but as @patrick says, you normally assign a callback function, like this. The time is milliseconds
setTimeout(func, 4000);
function func() {
alert('Do stuff here');
}
Just to add to what everyone else have said about setTimeout
:
If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.
You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':
var a = "world";
setTimeout(alert("Hello " + a), 2000);
To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.
var a = "world";
setTimeout(function(){alert("Hello " + a)}, 2000);
a = "Stack Overflow";
But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:
function callback(a){
return function(){
alert("Hello " + a);
}
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";
It will wait 2 seconds and then popup 'Hello world'.
If you really want to have a blocking (synchronous) delay
function (for whatsoever), why not do something like this:
<script type="text/javascript">
function delay(ms) {
var cur_d = new Date();
var cur_ticks = cur_d.getTime();
var ms_passed = 0;
while(ms_passed < ms) {
var d = new Date(); // Possible memory leak?
var ticks = d.getTime();
ms_passed = ticks - cur_ticks;
// d = null; // Prevent memory leak?
}
}
alert("2 sec delay")
delay(2000);
alert("done ... 500 ms delay")
delay(500);
alert("done");
</script>
There is the following:
setTimeout(function, milliseconds);
function which can be passed the time after which the function will be executed.
See: Window setTimeout()
Method.