Display an alert box after 3 seconds, 3000 milliseconds:
setTimeout(function(){ alert("Hello"); }, 3000);
Click the button to wait 3 seconds, then alert "Hello".
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Test</button> <script> function myFunction() {// w ww .j ava 2s . co m setTimeout(function(){ alert("Hello"); }, 3000); } </script> </body> </html>
The setTimeout()
method calls a function or evaluates an expression after a specified number of milliseconds.
The function is only executed once.
To repeat execution, use the setInterval()
method.
Use the clearTimeout()
method to prevent the function from running.
setTimeout(function, milliseconds, param1, param2, ...);
Parameter Values
Parameter | Description |
---|---|
function | Required. The function to be executed |
milliseconds | Optional. The number of milliseconds to wait before executing the code. If omitted, the value 0 is used |
param1, param2, ... | Optional. Additional parameters to pass to the function |
The setTimeout()
method returns a Number representing the ID value of the timer that is set.
Use this value with the clearTimeout()
method to cancel the timer.