This article will introduce to you the differences in the use of setTimeout() and setInterval() timers in JavaScript. (Recommended: "javascript tutorial")
setTimeout() method
setTimeout() method is waiting for the specified Execute a function after the number of milliseconds.
Syntax:
window.setTimeout(function, milliseconds); function : 第一个参数是要执行的函数 milliseconds : 表示执行前的毫秒数.
For example, we want a prompt box to pop up 2 seconds after the user presses the "Click me!" button.
The javascript code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<button onclick="setTimeout(gfg, 2000);">点击我!</button>
<script>
function gfg()
{
alert('欢迎来到PHP中文网!');
}
</script>
</body>
</html>Output:
Once the user presses the "Press Me" button, then after a pause of 2 seconds, a box will pop up.


##setInterval() method
setInterval()method Repeat a given function at every given time interval.
window.setInterval(function, milliseconds); function : 第一个参数是要执行的函数 milliseconds :表示每次执行之间的时间间隔的长度。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p>我会说“你好”很多次!</p>
<p id="GFG"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer()
{
document.getElementById("GFG").innerHTML += "<p>你好</p>";
}
</script>
</body>
</html>

The above is the detailed content of The difference between setTimeout() and setInterval() timers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!