The usage of setinterval and settimeout in JavaScript _javascript skills

Source: Internet
Author: User
Tags repetition setinterval time interval

SetTimeout

Describe

SetTimeout (CODE,MILLISEC)

The settimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.

Note: During the call process, you can use Cleartimeout (id_of_settimeout) to terminate

Parameters Description
Code Required, the JavaScript code string to be executed after the function to be invoked.
Millisec Required, the number of milliseconds to wait before executing the code.

Settimeinterval

SetInterval (code,millisec[, "Lang"])

Parameters Description
Code Required, the function to invoke or the code string to execute.
Millisec The time interval, in milliseconds, that is required to periodically execute or call code.

The SetInterval () method can call a function or a calculation expression in the specified period (in milliseconds).

JS Set delay:

Using setinterval and setting the delay function settimeout very similar. SetTimeout is used to delay a period of time and then perform an operation.

SetTimeout ("function", time) sets a timeout object SetInterval ("function", time) to set a timeout object

SetInterval for automatic repetition, settimeout will not repeat.

Cleartimeout (object) clears the set SetTimeout object Clearinterval (object) clears the SetInterval object that has been set

The SetInterval () method can call a function or a calculation expression in the specified period (in milliseconds).

Using the timer to implement JavaScript's deferred execution or repeated execution of the Window object provides two ways to implement the timer effect, respectively, Window.settimeout () and Window.setinterval. The former can cause a piece of code to run after a specified amount of time, while the latter can cause a piece of code to run once per specified time. Their prototypes are as follows: Window.settimeout (expression,milliseconds); Window.setinterval (Expression,milliseconds); Where expression can be a piece of code enclosed in quotes, it can also be a function name, which is called automatically by the system at the specified time, and when the function name is used as the calling handle, it cannot have any arguments, and when a string is used, the parameter to pass can be written to. The second parameter of the two method is milliseconds, which indicates the number of milliseconds that are delayed or repeated.

Here are two ways to describe each.

1. Window.settimeout method This method can delay the execution of a function, for example:

<script language= "JavaScript" type= "Text/javascript" >
<!--
 function hello () {alert ("Hello");} Window.settimeout (hello,5000);
-->
 </script>

This code will cause the page to open for 5 seconds before the dialog box "Hello" is displayed. The last sentence can also be written as: Window.settimeout ("Hello ()", 5000); Readers can appreciate their differences, which are also true in Window.setinterval methods. If you cancel the delay before the deadline arrives, you can use the Window.cleartimeout (Timeoutid) method, which receives an ID representing a timer. This ID is returned by the SetTimeout method, for example:

<script language= "JavaScript" type= "Text/javascript" >
<!--
function hello () {   
alert ("Hello");
}
var id=window.settimeout (hello,5000);
Document.onclick=function () {   
window.cleartimeout (ID);
 }
-->
</script>

In this way, if you want to suppress the display, simply click on any part of the page to execute the Window.cleartimeout method so that the timeout operation is canceled.

2. Window.setinterval method This method allows a function to be invoked at regular intervals, and is a very common method. If you want to cancel timed execution, like the Cleartimeout method, you can call the Window.clearinterval method. The Clearinterval method also receives the value returned by a setinterval method as an argument. For example://define a recurring call to Var id=window.setinterval ("somefunction", 10000); Cancel timed execution window.clearinterval (ID); The above code is used only to illustrate how to cancel a timed execution. In fact, there are many occasions where the SetInterval method is needed, and a stopwatch is designed to describe the purpose of the SetInterval function: The stopwatch will include two buttons and a text box to display the time. When the Start button is clicked, the minimum unit is 0.01 seconds, and the Click button stops timing, and the text box displays the elapsed time. Another button is used to clear the current time to zero. The implementation code is as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >  

Calling the timer to pass arguments whether it is window.settimeout or window.setinterval, you cannot take arguments with the function name as the calling handle, and you have to take parameters in many situations, which requires a solution. For example, for the function Hello (_name), it is used to display welcome information for the user name: Var username= "Jack";

Displays welcome information according to user name
function Hello (_name) {   
 alert ("Hello," +_name);
 }

At this point, it is not feasible to use the following statement to delay execution of the Hello function by 3 seconds:

Window.settimeout (Hello (userName), 3000);

This will cause the Hello function to execute immediately and pass the return value as the call handle to the SetTimeout function, and the result is not required by the program. You can achieve the desired result by using a string form:

Window.settimeout ("Hello (userName)", 3000);

The string here is a piece of JavaScript code, where the username represents the variable. But this kind of writing is not intuitive, and some occasions must use the function name, the following with a small trick to implement the call with a parameter function:

<script language= "JavaScript" type= "Text/javascript" > <!--var username= "Jack";
Displays welcome information according to user name
function Hello (_name) {    
alert ("Hello," +_name);
}
Creates a function that returns a parameterless function
_hello (_name) {return    
function () {       
hello (_name);    }}
Window.settimeout (_hello (userName), 3000);
 -->
</script>

This defines a function _hello, which receives a parameter and returns a function with no parameters, which uses the arguments of the external function inside the function to invoke it without using parameters. In the Window.settimeout function, _hello (userName) is used to return a function handle with no parameters, thus realizing the function of parameter passing.

The Window object has two main timing methods, settimeout and Setinteval, whose syntax is essentially the same, but the completed functionality differs.

The SetTimeout method is the timer program, which is what to do after the time. Just finish it.

The SetInterval method is to indicate that an operation is repeated at a certain time interval.

  JS Set delay:

Using setinterval and setting the delay function settimeout very similar. SetTimeout is used to delay a period of time and then perform an operation.

SetTimeout ("function", time) sets a timeout object

SetInterval ("function", time) sets a timeout object

SetInterval for automatic repetition, settimeout will not repeat.

Cleartimeout (object) clears the SetTimeout object that has been set

Clearinterval (object) clears the SetInterval object that has been set

If you implement the function of Setinerval with settimeout, you need to call yourself in the program you are executing. If you want to clear the counter you need to invoke different cleanup methods depending on the method you are using:

For example:

Tttt=settimeout (' Northsnow () ', 1000);
Cleartimeout (TTTT);

Or:

Tttt=setinterval (' Northsnow () ', 1000);
Clearinteval (TTTT);

Give an example:

<div id= "Liujincai" >
</div>
<input type= "button" name= "Start" value= "Start" onclick= " Startshow (); ' >
<input type= "button" name= "Stop" value= "Stop" onclick= "Stop ();" >
<script language= "JavaScript" >  
var intvalue=1;  
var timer2=null;  
function Startshow ()  {   
 liujincai.innerhtml=liujincai.innerhtml + "" + (Intvalue + +). toString ();   
Timer2=window.settimeout ("Startshow ()");  
function Stop ()  {   
 window.cleartimeout (timer2);  
 }
</script>

Or:

<div id= "Liujincai" >
</div>
<input type= "button" name= "Start" value= "Start" onclick= ' timer2= Window.setinterval ("Startshow ()");//startshow (); ' >
<input type= "button" name= "Stop" value= "Stop" onclick= "Stop ();" >
<script language= "JavaScript" >  
 var intvalue=1;  
var timer2=null;  
 function Startshow ()  {   
 liujincai.innerhtml=liujincai.innerhtml + "" + (Intvalue + +). ToString ()  
 ;  
 function Stop ()  {   
 window.clearinterval (timer2);  
}
</script>

The above content is small to introduce to you about JavaScript in the use of setinterval and settimeout, I hope to learn setinterval and settimeout related knowledge to help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.