You don't know the proper use of the JAVASCRIPT--ITEM23 timer

Source: Internet
Author: User
Tags setinterval

1. Timer overview

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(expressionwindow.setInterval(expression

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.

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)Set a Timeout object
    • setInterval("function",time)Set a Timeout object

SetInterval for automatic repetition, settimeout does not repeat.

    • clearTimeout(对象)Clears the SetTimeout object that has been set
    • clearInterval(对象)Clears the SetInterval object that has been set

Use timers to implement deferred or repetitive JavaScript execution.

2. Specific Use

1. Window.settimeout Method

The method can defer execution of a function, for example:

function hello(){     alert("hello"); } window.setTimeout(hello,5000);  

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:

function hello(){       alert("hello"var id=window.setTimeout(hello,5000); document.onclick=function(){      window.clearTimeout(id); }  

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:

//定义一个反复执行的调用 id=window.setInterval("somefunction",10000//取消定时执行 window.clearInterval(id

3. Demo Little Practice

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:

<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"> <!--//Get form fields in a formvartxt=document.forms[0].elements["Txt1"];varbtnstart=document.forms[0].elements["Btnstart"];varbtnreset=document.forms[0].elements["Btnreset"]//define the ID of the timervarId//per 10 milliseconds This value increases by 1varSeed=0; btnstart.onclick= function(){       //According to the button text to determine the current operation      if( This. value=="Start"){//Make button text stop               This. value="Stop";//Make reset button unavailableBtnreset.disabled=true;//Set timer, jump once per 0.01sId=window.setinterval (Tip,Ten); }Else{//Make button text start               This. value="Start";//Make reset button availableBtnreset.disabled=false;//Cancel TimerWindow.clearinterval (ID); } }//reset buttonbtnreset.onclick= function(){Seed=0; }//Let the stopwatch jump one cell function tip(){seed++; txt.value=seed/ -; }//--></script> 
3. Passing parameters to the 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"//根据用户名显示欢迎信息 function hello(_name){       alert("hello,"

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:

var  username= "Jack" ; //display welcome information based on user name  function  hello  Span class= "Hljs-params" > (_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, it is used _hello(userName) to return a function handle without parameters, thus realizing the function of parameter passing.

4. Correct understanding of Timer "timing" function

First look at a piece of code

display(){    alert(hello);}setTimeout("display()", 3000);alert("你首先看到的是我!")

What does the code output first? The answer is obvious in the program. Why is it?

Beginners may misunderstand the JavaScript timer, think that they are threads, in fact, JavaScript is running in a single thread, and the timer is only scheduled to execute at some time in the future, and the specific execution time is not guaranteed, because in the life cycle of the page, Different times may have other code in the process of controlling JavaScript. The browser is simply responsible for sorting and assigning a code to run at a certain point in time.

The following is the JavaScript thread, which represents the JavaScript process timeline.

In addition to the JavaScript execution process, there is a code queue that needs to be executed during the next idle time of the process, and as the page progresses over its lifetime, the code is added to the column in the order of execution, for example: When a button is pressed, its event handling is added to the queue. and execute within the next possible time.

The way the timer works on the queue is that when a specific time passes, the code is inserted, and note that adding to the queue does not mean that it will execute immediately, but that it will execute as soon as possible, setting a timer that executes after 250ms, does not mean that 250ms will execute immediately, It will only indicate that it is added to the queue after 250ms, and if the point-in-time queue is idle, then this code will be executed.

Take a look at the following code:

var btn = document.getElementById("mybtn");    function () {        setTimeout(function () {            document.getElementById("message""mymessage";            //其它代码        250);    }

The most important thing to note about timers is that the specified time interval indicates when the code for the timer is added to the queue, not when the code is executed. For the process timeline for this onclick process please see:

Series Article Navigation:

1, you do not know the Javascript–item1 strict mode

2, you do not know the javascript–item2 floating point precision

3, you do not know the javascript–item3 implicit coercion

4, you do not know the JAVASCRIPT–ITEM4 basic type and basic packaging type (reference type)

5, you do not know the JAVASCRIPT–ITEM5 global variables

6, you do not know the JAVASCRIPT–ITEM6 var pre-parsing and function declaration promotion (hoist)

7. Javascript–item7 functions and (named) function expressions that you do not know

8. You do not know the JAVASCRIPT–ITEM8 function, method, constructor call

9, you do not know javascript–item9 call (), apply (), bind () and callback

10, you do not know the JAVASCRIPT–ITEM10 closure (closure)

11, you do not know the Javascript–item11 arguments object

12, you do not know the javascript–item12 undefined and null

13, you do not know the Javascript–item13 understanding prototype, getprototypeof and _ proto_

14, you do not know the JAVASCRIPT–ITEM14 use prototype a few notes

15, you do not know the JAVASCRIPT–ITEM15 prototype prototype and prototype chain detailed

16. What you don't know about the javascript–item16 for loop and the for...in loop

17, you do not know the JAVASCRIPT–ITEM17 cycle and prototype the last few tips

18. Javascript–item18 JScript bugs and memory management you don't know

19, you do not know the javascript–item19 execution context (execution context)

20. JAVASCRIPT–ITEM20 scope and scope chain you don't know (scope chain)

21, you do not know the javascript–item21 drift of this

22, you do not know the Javascript–item22 Date object full parse

23, you do not know the reasonable use of the JAVASCRIPT–ITEM23 timer

Continuous update ...

Copyright NOTICE: This article is the original article, reproduced please specify: http://blog.csdn.net/i10630226

You don't know the proper use of the JAVASCRIPT--ITEM23 timer

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.