JS set delay: js in SetInterval and settimeout usage

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" />
< input type= "button" Span style= "color: #ff0000;" > Value= "resets name=" Btnreset "/>
</ form>
</< Span style= "color: #800000;" >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>

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>

JS set delay: js in SetInterval and settimeout usage

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.