Home >Web Front-end >JS Tutorial >How to use the setTimeout function in JavaScript?
The setTimeout function in JavaScript is to call a function or calculation expression after a specified number of milliseconds. Its syntax is "setTimeout(func,ms)". The return value is an ID, which can be passed Give "clearTimeout" function to cancel execution.
Browser support
Method | Chrome | Internet Explorer / Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
setTimeout() | 1.0 | 4.0 | 1.0 | 1.0 | 4.0 |
Example Code
"Hello" pops up after 3 seconds (3000 milliseconds):
var myVar; function myFunction() { myVar = setTimeout(alertFunc, 3000);} function alertFunc() { alert("Hello!");}
Modify the text in the input box at 2, 4, and 6 seconds:
var x = document.getElementById("txt"); setTimeout(function(){ x.value = "2 秒" }, 2000); setTimeout(function(){ x.value = "4 秒" }, 4000); setTimeout(function(){ x.value = "6 秒" }, 6000);
Use clearTimeout() to prevent the execution of the function:
var myVar; function myFunction() { myVar = setTimeout(function(){ alert("Hello") }, 3000); } function myStopFunction() { clearTimeout(myVar); }
Recommended tutorial: "JS Tutorial"
The above is the detailed content of How to use the setTimeout function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!