Setinterval and setTimeout usage in JS

Source: Internet
Author: User
Tags repetition

Setinterval and setTimeout usage in S

Set latency in JS:

Setinterval and setTimeout
Very similar. SetTimeout is used to perform an operation after a delay period.

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

Setinterval indicates automatic repetition, and setTimeout does not.

Cleartimeout (object) clears the set setTimeout object
Clearinterval (object) clears the set setinterval object

Use a timer to implement deferred or repeated JavaScript Execution
The window object provides two methods to implement the timer effect, 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 time. Their prototype is as follows:
Window. setTimeout (expression, milliseconds );
Window. setinterval (expression, milliseconds );
Expression can be a piece of code enclosed in quotation marks or a function name. at the specified time, the system automatically calls the function, when the function name is used as the call handle,
You cannot include any parameters. When using a string, you can write the parameters to be passed. The second parameter of the two methods is milliseconds, which indicates the number of milliseconds of delay or repeated execution. Lower
This section describes two methods.

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 enable the page to open for 5 seconds and then display the "hello" dialog box ". The last sentence can also be written as follows:
Window. setTimeout ("Hello ()", 5000 );
Readers can understand their differences. They also have such properties in the window. setinterval method.
If the execution is canceled before the delay period expires, you can use the window. cleartimeout (timeoutid) method, which receives an ID, indicating 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, to cancel the display, you only need to click any part of the page to execute the window. cleartimeout method, so that the timeout operation is canceled.

2. Window. setinterval Method
This method is a common method that allows a function to be called at regular intervals. If you want to cancel scheduled execution, it is similar to the cleartimeout method, you can call
Window. clearinterval method. The clearinterval method also receives the value returned by a setinterval method as a parameter. For example:
// Define a call that is executed repeatedly
VaR id = Window. setinterval ("somefunction ()", 10000 );
// Cancel scheduled execution
Window. clearinterval (ID );
The above code is only used to describe how to cancel a scheduled execution. In fact, the setinterval method is used in many cases. Next we will design a stopwatch to introduce the purpose of the setinterval function: This stopwatch will contain two buttons and a text box for displaying time. Start timing when you click the start button. The minimum unit is 0.01 seconds. click the button again to stop timing. The text box shows 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">
<HTML>
<Head>
<Title> new document </title>
</Head>
<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>
</Html>
<Script language = "JavaScript"
Type = "text/JavaScript">
<! --
// Obtain the form field in the form
VaR TXT = Document. Forms [0]. elements ["txt1"];
VaR btnstart = Document. Forms [0]. elements ["btnstart"];
VaR btnreset = Document. Forms [0]. elements ["btnreset"]
// Define the timer ID
VaR ID;
// Increase the value by 1 every 10 milliseconds.
VaR seed = 0;

Btnstart. onclick = function (){
// Determine the current operation based on the button text
If (this. value = "start "){

// Make the button text Stop

This. value = "stop ";

// Make the 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 the reset button available

Btnreset. Disabled = false;

// Cancel the timer

Window. clearinterval (ID );
}
}

// Reset button
Btnreset. onclick = function (){
Seed = 0;
}
// Jump the stopwatch to a grid
Function tip (){
Seed ++;
TXT. value = seed/100;
}
// -->
</SCRIPT>

7.4.3 Pass parameters to the timer call
Whether it is window. setTimeout or window. setinterval, parameters cannot be included when using the function name as the call handle. In many cases, parameters must be included, which requires a solution. For example, for the hello (_ name) function, it is used to display the welcome information for the user name:
VaR username = "Jack ";
// Display the welcome information based on the user name
Function Hello (_ name ){
Alert ("hello," + _ name );
}
At this time, if you attempt to use the following statement to delay the hello function execution by 3 seconds, it is not feasible:
Window. setTimeout (Hello (username), 3000 );
This will enable the hello function to be executed immediately and pass the returned value to the setTimeout function as the call handle. The result is not required by the program. You can use a string to achieve the desired result:
Window. setTimeout ("Hello (username)", 3000 );
The string here is a piece of JavaScript code, where username represents a variable. However, this method is not intuitive enough, and function names must be used in some cases. Here is a tips to call a function with parameters:
<Script language = "JavaScript"
Type = "text/JavaScript">
<! --
VaR username = "Jack ";
// Display the welcome information based on the user name
Function Hello (_ name ){
Alert ("hello," + _ name );
}
// Create a function to return a non-Parameter Function
Function _ Hello (_ name ){
Return function (){

Hello (_ name );
}
}
Window. setTimeout (_ Hello (username), 3000 );
// -->
</SCRIPT>
A function _ Hello is defined here, which is used to receive a parameter and return a function without a parameter. An external function parameter is used inside the function to call it, no parameters are required. In the window. setTimeout function, _ Hello (username) is used to return a function handle without parameters, thus implementing the function of passing parameters.

Window objects have two main timing Methods: setTimeout and setinteval. Their syntaxes are basically the same, but their functions are different.

The setTimeout method is a Timer Program, that is, after what time. After the job is finished, pull it down.

The setinterval method indicates that an operation is executed repeatedly at a certain interval.

Set latency in JS:

Setinterval and setTimeout
Very similar. SetTimeout is used to perform an operation after a delay period.

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

Setinterval indicates automatic repetition, and setTimeout does not.

Cleartimeout (object) clears the set setTimeout object
Clearinterval (object) clears the set setinterval object

If you use setTimeout to implement the setinerval function, you need to regularly call yourself in the executed program. To clear a counter, you need to call different clearing methods based on the method used:

Example: tttt = setTimeout ('northsnow () ', 1000 );

Cleartimeout (tttt );

Or:

Tttt = setinterval ('northsnow () ', 1000 );

Clearinteval (tttt );

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

 

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.