In the JS application, the function of the timer is to set a time to execute a function, or to repeat a function every few seconds. This involves three function methods: SetInterval (), SetTimeout (), Clearinterval (), this article will be around the use of three functions, to achieve the function of the timer, the need for friends can come over to the reference, like can point wave praise, Or look at me, I hope to help you.
Application Requirements for timers:
1. Set a time, when the time arrives to execute function ———— such as: Countdown jump page and so on.
2. Repeat a function every once in a while ———— such as a ticket-grabbing software, such as setting up a page for 500 milliseconds and repeating it.
JS Timer:
That's what the rookie tutorial says. The--JS timer has the following two methods:
SetTimeout (): Invokes a function or evaluates an expression after the specified number of milliseconds.
SetInterval (): Invokes a function or evaluates an expression by the specified period (in milliseconds). The Clearinterval method keeps calling the function until the call or window is closed.
Use syntax:
SetTimeout (): SetTimeout (CODE,MILLISEC)
SetInterval (): SetInterval (code,millisec[, "Lang"])
Parameters: Code ———— the function to be called or the string to execute. Millisec ———— time (computed by default milliseconds), Lang ———— Optional. JScript | VBScript | JavaScript ()
However, the difference between settimeout () and SetInterval () is that
SetTimeout (): When the method execution completes the timer stops immediately (but the timer is still in, just useless);
SetInterval (): When the method execution completes, the timer does not stop, after each [interval] for such a long time will re-execute the corresponding method [function], until we manually clear the timer;
The meaning is:
SetTimeout () time is only executed once, setinterval () will not stop, will execute the corresponding function continuously until we manually pause or the window is closed.
Countdown Jump Demo Explanation:
class="Time" > Please wait <span id="dd" >5</span> seconds </div> JS section: Function Run () { var s = document.getElementById ("dd"); if (s.innerhtml = = 0) { window.location.href = "Https://juejin.im/user/58714f0eb123db4a2eb95372/article"; Clearinterval (Run ()); } s.innerhtml = s.innerhtml-1; } Window.setinterval ("Run ();", 1000);
JS Timer usage detailed--settimeout (), SetInterval (), cleartimeout (), Clearinterval ()