Reprint---javascript timer summary

Source: Internet
Author: User
Tags repetition

Reprint: http://www.jb51.net/article/40193.htm

JS Set delay:
Using setinterval and setting the delay function settimeout very similar. SetTimeout used to delay a period of time before doing an operation.
SetTimeout ("function", time) sets a timeout object
SetInterval ("function", time) sets a timeout object
SetInterval for automatic repetition, settimeout does not repeat.
Cleartimeout (object) clears the SetTimeout object that has been set
Clearinterval (object) clears the SetInterval object that has been set
Use timers for deferred or repetitive JavaScript execution
The Window object provides two methods to achieve the effect of the timer, namely Window.settimeout () and Window.setinterval. The former allows a piece of code to run after a specified time, while the latter allows a piece of code to run once every 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 quotation marks, or a function name, the function is automatically called when the function name is used as the invocation handle, and when a string is used, it can be written to the parameter to be passed. The second parameter of two methods is milliseconds, which indicates the number of milliseconds to delay or repeat execution. Two methods are described below.

1. Window.settimeout method
The method can defer 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 5 seconds after the dialog "Hello" is displayed. The last sentence can also be written as: Window.settimeout ("Hello ()", 5000);

Can understand their differences, in the Window.setinterval method also has such a nature.
If you cancel deferred execution before the delay period arrives, you can use the Window.cleartimeout (Timeoutid) method, which receives an ID that represents 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>

This way, if you want to suppress the display, simply click on any part of the page and execute the Window.cleartimeout method, which causes the timeout operation to be canceled.

2. Window.setinterval method
This method allows a function to be called once every fixed time, which is a very common method. If you want to cancel timed execution, similar to the Cleartimeout method, you can call the Window.clearinterval method. The Clearinterval method also receives a value returned by the SetInterval method as a parameter. For example:

To define a recurring call
var id=window.setinterval ("somefunction", 10000);
Cancel timed execution
Window.clearinterval (ID);

The above code is only used to illustrate how to cancel a timed execution. In fact, in many cases need to use the SetInterval method, the following will design a stopwatch, 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, when the button is clicked again to stop the timing, and the text box displays the elapsed time. Another button is used to clear the current time. The implementation code is as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<title> New Document </title>
<body>
<form action= "somepage.asp" >
<input type= "text" value= "0" name= "txt1"/>
<input type= "button" value= "Start" name= "Btnstart"/>
<input type= "button" value= "reset" name= "Btnreset"/>
</form>
</body>
<script language= "JavaScript" type= "Text/javascript" >
<!--
Get form fields in a form
var txt=document.forms[0].elements["Txt1"];
var btnstart=document.forms[0].elements["Btnstart"];
var btnreset=document.forms[0].elements["Btnreset"]
Define the ID of the timer
var id;
This value increases by 1 per 10 milliseconds
var seed=0;
Btnstart.onclick=function () {
Determines the current operation based on the button text
if (this.value== "start") {
Change the button text to stop
This.value= "Stop";
Make reset button unavailable
Btnreset.disabled=true;
Set the timer to jump every 0.01s
Id=window.setinterval (tip,10);
}else{
Change the button text to start
This.value= "Start";
Make reset button available
Btnreset.disabled=false;
Cancel Timer
Window.clearinterval (ID);
}
}
Reset button
Btnreset.onclick=function () {
Seed=0;
}
Let the stopwatch jump a grid
Function Tip () {
seed++;
txt.value=seed/100;
}
-
</script>

7.4.3 passing parameters to a timer call
Either Window.settimeout or Window.setinterval, you cannot take arguments with the function name as the invocation handle, and in many cases you have to take parameters, which you need to resolve. For example, function hello (_name), which is used to display a welcome message for a user name:

var username= "Jack";
Display welcome information based on user name
function Hello (_name) {
Alert ("Hello," +_name);
}

At this point, it is not feasible to attempt to use the following statement to delay the Hello function for 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 username represents a variable. But this is not intuitive, and some occasions must use the function name, following a small trick to implement the call with the parameter function:

<script language= "JavaScript" type= "Text/javascript" >&NBSP;
<!-- 
var username= "Jack";  
//Displays the welcome message according to the user name  
Function Hello (_name) { 
       alert (" Hello, "+_name);  

//Create a function that returns a parameterless function  
function _hello (_name) { 
        return function () { 
              Hello (_name);  
      } 

Window.settimeout (_hello (userName),  
//--> 
</script> 

This defines a function _hello, which receives a parameter and returns a function with no parameters, using the parameters of the external function inside the function to invoke it without using parameters. In the Window.settimeout function, the function of parameter passing is achieved by using _hello (UserName) to return a function handle without parameters.
The Window object has two main timing methods, namely settimeout and setinteval their syntax is basically the same, but the completed function is different.
The SetTimeout method is a timed procedure, that is, what to do after what time. When you're done.
The SetInterval method is to represent the interval for a certain amount of time to perform an operation repeatedly.
JS Set delay:
Using setinterval and setting the delay function settimeout very similar. SetTimeout used to delay a period of time before doing an operation.
SetTimeout ("function", time) sets a timeout object
SetInterval ("function", time) sets a timeout object
SetInterval for automatic repetition, settimeout does 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 Setinerval functionality with settimeout, you will need to call yourself again and again in the program you are executing. If you want to purge counters that need to be different from the method used, call different cleanup methods:
For example:

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

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

Reprint---javascript timer summary

Related Article

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.