JavaScript Timer and Example _javascript skills

Source: Internet
Author: User
Tags repetition setinterval 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
Using timers to implement JavaScript deferred or repeated execution
The Window object provides two methods to implement the timer effect, namely 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:
Copy Code code as follows:

<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:
Copy Code code as follows:

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:
Copy Code code as follows:

<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 makes a function to be called once every fixed time, 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:
Copy Code code as follows:

Define a call that executes repeatedly
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:
Copy Code code 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 is increased by 1 per 10 milliseconds
var seed=0;
Btnstart.onclick=function () {
To determine the current operation based on the button text
if (this.value== "start") {
Make button text stop
This.value= "Stop";
Make the reset button unavailable
Btnreset.disabled=true;
Set timer, jump once per 0.01s
Id=window.setinterval (tip,10);
}else{
Change the button text to start
This.value= "Start";
Make the reset button available
Btnreset.disabled=false;
Cancel Timing
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 Pass parameters to timer calls
Whether it's window.settimeout or window.setinterval, you can't take arguments with the function name as the calling handle, and you have to take parameters on many occasions, which requires a workaround. For example, for the function Hello (_name), it is used to display welcome information for the user name:
Copy Code code as follows:

var username= "Jack";
Show welcome information based on 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:
Copy Code code as follows:

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:
Copy Code code as follows:

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:
Copy Code code as follows:

<script language= "JavaScript" type= "Text/javascript" >
<!--
var username= "Jack";
Show welcome information based on user name
function Hello (_name) {
Alert ("Hello," +_name);
}
Creates a function that returns a parameterless function
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:
Copy Code code as follows:

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

Or:
Copy Code code as follows:

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

Give an example:
Copy Code code as follows:

<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:
Copy Code code as follows:

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