Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript timer
In javascript, there are two dedicated functions for timers, they are:
1. Countdown timer: timename=setTimeout("function();",delaytime);
2. Loop timer: timename =setInterval("function();",delaytime);
Function() is the event function to be executed when the timer is triggered. It can be one function, several functions, or a javascript statement. To use; separate; delaytime is the interval time, in milliseconds.
A countdown timer triggers an event after a specified time, while a loop timer triggers an event repeatedly when the interval arrives. The difference is that the former only works once, while the latter works continuously.
The countdown timer is generally used when the page only needs to be triggered once. For example, after clicking a button, the page will jump to the corresponding site after a certain period of time. It can also be used to determine whether a visitor is on your site. "Regular customer", if not, you can jump to the corresponding site in 5 seconds or 10 seconds, and then tell him that he can press a certain button somewhere to quickly enter if he comes back in the future.
Loop timers are generally used for effects that need to be executed repeatedly on the site, such as a javascript scroll bar or status bar. They can also be used to represent the background of the page with a picture of flying snow. These events need to be run at intervals.
Sometimes we also want to remove some added timers. In this case, we can use clearTimeout(timename) to turn off the countdown timer, and use clearInterval(timename) to turn off the loop timer.
Example 1:
function count() {
setTimeout("alert('Three seconds are up')",3000)
}
Example 2:
<Script><script language="JavaScript" type="text/javascript"></p>
<p><br>var sec = 0; <br>timerID = setInterval("count()",1000);</p>
<p>function count() {<br> num.innerHTML = sec++;<br>}</p>
<p></Script>
Stay time:
0Seconds
Example 3:
var str = "This is an online auction website, please enjoy your shopping!";
var seq = 0;
function scroll() {
msg = str.substring(0, seq+1);
banner.innerHTML = msg;
seq++;
if (seq >= str.length) seq = 0;
}
< Body onLoad="setInterval('scroll()',500)">