Home>Article>Web Front-end> How to use the setTimeout function in JavaScript?

How to use the setTimeout function in JavaScript?

Guanhui
Guanhui Original
2020-06-24 15:48:09 4396browse

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.

How to use the setTimeout function in JavaScript?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn