SetInterval and settimeout Timer usage _javascript techniques in JavaScript

Source: Internet
Author: User
Tags repetition setinterval time interval

Example one:

View Demo Download source code

The settimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds, while SetInterval () invokes the function or expression at the specified number of milliseconds, until clearinterval clears it. That is, settimeout () is executed only once, and setinterval () can be executed multiple times. The parameters for two functions are the same, the first is the code or handle to execute, and the second is the number of milliseconds to delay.

SetTimeout usage

The use of the SetTimeout function is as follows:

var Timeoutid = Window.settimeout (func, [Delay, param1, param2, ...]); 

Timeoutid: The timer ID number, which can be used to clear the timer in the Cleartimeout () function.

func: The function that is executed.

Code: (alternative syntax) a coded string to be executed.

delay: delay time, in units of milliseconds. If not specified, the default is 0.

We can use Window.settimeout or settimeout, two of them are basically the same, except that the SetTimeout function is referenced as a property of the global Window object.

application Example:

function timeout () { 
 document.getElementById (' res '). Innerhtml=math.floor (Math.random () *100 + 1); 
} 

settimeout ("timeout ()", 5000); 

When code executes, call the timeout () function after 5 seconds.

SetInterval usage

The parameters and usages of the setinterval function are the same as the settimeout function, please refer to the use of the settimeout function above. The difference is that setinterval executes the Func or code codes at every interval.

application Example:

var tt = ten; 
function Timego () { 
 tt--; 
 document.getElementById ("tt"). InnerHTML = TT; 
 if (tt==0) { 
  window.location.href= '/'; 
  return false; 
 } 
} 

The function Timego () defines the content that the page element #tt display, and when TT equals 0 o'clock, the page is directed to the homepage. Then we define a timer timer and use SetInterval () to call Timego () every 1 seconds. This timego will be performed 10 times, each time the number TT will be reduced by 1 until 0. So if you want to stop the timer, you can use the following code:

 
 

Code execution, 10 seconds after the page to jump to the homepage.

In fact, settimeout () can also implement a function every once in a while, but we still make a simple difference between using settimeout and setinterval. In addition, JavaScript is running in a single-threaded way in the browser's JavaScript engine, the actual application of complex tasks in the need to queue execution, which may lead to timer time is not allowed, this problem in large applications need to consider, this article does not delve into.

Example two:

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

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. Its implementation

The 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 ()", 2000); 
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>

Although SetInterval and settimeout are used as timers, their applications are different.

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.