This article mainly introduces the relevant information of JavaScript timer setTimeout() and setInterval() in detail, which has certain reference value. Interested friends can refer to it
The examples of this article are We have shared the specific method of JavaScript timer for your reference. The specific content is as follows
1. Call setTimeout() with timeout
As the name suggests, The timeout call means calling after a period of time (how many milliseconds to wait before executing the code)
setTimeout(), which can receive two parameters:
1. The code or function to be executed
2. Milliseconds (how many milliseconds to wait before executing the code)
function test(){ alert("孙悟空"); } setTimeout(test,2000); //2s后弹出 “孙悟空”
clearTimeout()
clearTimeout means clearing the timer. You can use it to cancel unexecuted calls
var timmer=function test(){ alert("孙悟空"); } setTimeout(test,2000); //2s后弹出 “孙悟空” clearTimeout(timmer); //取消定时器,因为前者在两秒后调用,调用之前已经取消相当于什么也没发生
2. Intermittent calls to setInterval()
Intermittent calling is to repeatedly execute the code within a specified period of time. The vernacular is "call it once, call it once"
setInterval() also receives two parameters, which are the same as the former:
1. Code or function to be executed
2. Milliseconds (how many milliseconds to wait before executing the code)
function test(){ alert("孙悟空"); } setInterval(test,2000); //每隔2s后弹出一次 “孙悟空”
clearInterval()
clearInterval() is used in the same way as clearTimeout() and is also a clear timer method
var num=0; var max=10; function test(){ num++; if (num==max){ clearInterval(timer); //累加到10时清除清定时器 alert("这里有"+num+"个孙悟空"); //这里有10个孙悟空 } } timer=setInterval(test,500);
In the above example , the variable num is incremented every 0.5s. When it reaches the maximum value, the previously set timer will be cleared (intermittent call).
This mode can also be implemented using timeout calls
var num=0; var max=10; function test(){ num++; if (num Copy after login
The above is the detailed content of Detailed explanation of setTimeout() and setInterval() in JavaScript timers. For more information, please follow other related articles on the PHP Chinese website!