tags:

views:

1103

answers:

7

Is there some function like delay() or wait() for delaying executing of the JavaScript code for a specific number of milliseconds?

+3  A: 

You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!

Patrick
+13  A: 

There is the

setTimeout( expression, timeout );

function which can be passed the time after which the expression will be executed.

Abhinav
A: 

+1 on setTimeout, I'd vote but I'm at quota

DevelopingChris
+4  A: 

You can also use window.setInterval() to run some code repeatedly at a regular interval.

rcoup
+5  A: 

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');
}
Flubba
+4  A: 

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 = "Stac Overflow";

It will wait 2 seconds and then popup 'Hello world'.

Marius
A: 
function data(id) { function data2() { alert("ss"); } }

Iwat to alert ss; how canwe done that on click in data(2);

manu