SetInterval and settimeout usage in JS

Source: Internet
Author: User
Tags repetition

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 set SetTimeout object Clearinterval (object) clears the SetInterval object that has been set

Using timers to implement deferred execution of JavaScript or to repeat the Window object provides two ways to achieve the effect of the timer, respectively 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); Readers can appreciate their differences, and in the Window.setinterval method there is the same 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://define a recurring call to Var id=window.setinterval ("somefunction", 10000); Cancel timed execution of 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"> 
<HTML>
<Head>
<title>New Document</title>
</Head>
<Body>
<formAction= "Somepage.asp">
<inputtype= "text"value= "0"name= "Txt1"/>
<inputtype= "button"value= "Start"name= "Btnstart"/>
<inputtype= "button"value= "Reset"name= "Btnreset"/>
</form>
</Body>
</HTML>

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

Passing parameters to a timer call, whether window.settimeout or window.setinterval, cannot take arguments when using the function name as the invocation handle, and in many cases it is necessary to have parameters, which requires a workaround. For example, function hello (_name), which is used to display a welcome message for the 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" > <!--var username= "Jack";

Display welcome information based on 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), 3000);

-

</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);

Or:

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

Clearinteval (TTTT);

To 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 ()", 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>

Another example: Resend the SMS Verification Code button, can only send an instance of the verification code once every 15 seconds

var wait = 15;
function Countdown () {
if (wait = = 0) {
$ ("#btnReSendMessage"). attr ("disabled", false);
$ ("#btnReSendMessage"). Val ("Resend");
wait = 15;
} else {
$ ("#btnReSendMessage"). attr ("Disabled", true);
$ ("#btnReSendMessage"). Val ("Resend (" + Wait + ")");
wait--;
SetTimeout (function () {
Countdown ()
},
1000);
}
}

$ ("#btnReSendMessage"). Click (function () {
Resendsmsmessage ($ ("#txtMessageCode"). Val ());
Countdown ();
})

SetInterval and settimeout usage in JS

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.