The setTimeout()
method calls a function
after a specified number of milliseconds.
setTimeout()
executes code after a specified amount of time.
setTimeout()
method accepts two arguments:The first argument can be either a string containing JavaScript code or a function.
The following code runs an document.writeln after 1 second:
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
setTimeout(function() { <!--from w w w . j a va 2 s. c o m-->
document.writeln("Hello world!");
},
1000
);
</script>
</body>
</html>
setTimeout |
Yes | Yes | Yes | Yes | Yes |
setTimeout(function,milliseconds,lang)
Parameter | Description |
---|---|
function | Required. The function that will be executed |
milliseconds | Required. The number of milliseconds to wait before executing the code |
lang | Optional. The scripting language: JScript | VBScript | JavaScript |
An integer ID value of the timer.
Use this value with the clearTimeout() method to cancel the timer.
The following code shows how to Display an alert box after 3 seconds.
<!DOCTYPE html>
<html>
<body>
<!--from w ww . j a v a 2s. co m-->
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
setTimeout(function(){console.log("Hello")}, 3000);
}
</script>
</body>
</html>
The code above is rendered as follows:
setTimeout()
returns a numeric ID for the timeout.
The ID can be used to cancel the timeout.
To cancel a pending timeout, use the clearTimeout()
method and pass in the timeout ID:
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
var timeoutId = setTimeout(function() {
document.writeln("Hello world!");
}, 1000); <!-- ww w . j a v a 2s . c o m-->
clearTimeout(timeoutId);
</script>
</body>
</html>
The following code set the timeout according to a value:
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
var num = 0;
var max = 10;
function incrementNumber() { <!-- w w w . java2 s . c o m-->
document.writeln(num++);
//if the max has not been reached,
//set another timeout
if (num < max) {
setTimeout(incrementNumber, 500);
} else {
document.writeln("Done");
}
}
setTimeout(incrementNumber, 500);
</script>
</body>
</html>