When you make a Web page dynamic, you're bound to meet some requirements that require a program to wait a long time before it starts to execute, just like in our life, and then start doing something later. In JavaScript mainly through the timer to achieve such requirements, this article will make a summary of the timer, is a detailed usage summary of settimeout ().
I. The difference between setinterval and settimeout
SetInterval
The SetInterval () method invokes a function or evaluates an expression (in milliseconds) in the specified period.
Grammar:
SetInterval (function expression, number of milliseconds);
SetInterval () will not stop calling functions until Clearinterval () is called or the window is closed, and the ID value returned by setinterval () can be used as a parameter to the Clearinterval () method.
SetTimeout
The SetTimeout () method is used to call a function or evaluate an expression (in milliseconds) after a specified number of milliseconds
Grammar:
SetTimeout (function expression, number of milliseconds);
SetTimeout () Executes functions only once, and if multiple calls are required, setinterval () can be used, or setTimeout () is called again in the function body
Difference
As can be seen from the above analysis, the main differences between SetTimeout and SetInterval are:
The SetTimeout () method runs only once, which means that when the set time is reached, the specified code is run, the end is finished, and if you want to execute the same function again, you can call SetTimeout () again in the body of the function to achieve the effect of the loop call.
SetInterval () is a loop execution that executes the corresponding function or expression every time the specified interval is reached, and is the real timer.
Two. Use of SetTimeout ()
First write the simplest demo, as follows:
1 <! DOCTYPE html> 2 3 4 <meta charset= " Utf-8 "> 5 <script> 6 setTimeout (" alert (' Hello ') ", +); 7 </script> 8 9 <body>ten </body>
The page will pop up after 2 seconds, note that settimeout will not be repeated automatically!
Of course, settimeout can also perform function, and can be repeatedly executed!
You can see the text numbers in the H1 increment in one second!
More flexible is that you can also specify the number of times to repeat execution, as follows:
The number in the If judgment is the condition used to limit the number of repeated executions.
Three. Cleartimeout ()To use Cleartimeout (), we need to set settimeout (), give this settimeout () a name, this name is Timeoutid, when we stop, is to use this timeoutid to halt
1 <! DOCTYPE html> 3 4 <meta charset=" utf-8 "> 5 <script> 6 var timeid= setTimeout ("alert (' Hello ')", 2000 cleartimeout (Timeid); </script> 9 10 <body>12
The warning box that popped up after 1 seconds was halted by nature.
JS in settimeout () Usage Summary