Learn JavaScript with me timer _javascript tips

Source: Internet
Author: User
Tags setinterval

I. Overview of the Timer

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

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.

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

Use the timer to implement the JavaScript delay or repeat execution.

Second, the specific use

1. Window.settimeout method

This method can delay the execution of a function, for example:

function Hello () { 
 alert ("Hello"); 
} 

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:

 
 

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:

function Hello () { 
 alert ("Hello"); 
} 
var id=window.settimeout (hello,5000); 
Document.onclick=function () { 
 window.cleartimeout (ID); 
} 

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:

Defines a recurring call 
to Var id=window.setinterval ("somefunction", 10000); 
Cancel timed execution 
window.clearinterval (ID); 

3. Challenges

The above code is used only to illustrate how to cancel a timed execution. In fact, many occasions need to use the SetInterval method, following a topic with you: design a stopwatch to introduce the use 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 the timer, the text box shows the elapsed time, and the other button is used to clear the current time. Everyone first hands-on practice, the next article for everyone to reveal the answer, click to see the answer: "JavaScript design simple stopwatch timer"

Third, to the timer call pass parameters

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:

var username= "Jack"; 
Displays welcome information according to 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:

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

var username= "Jack"; 
Displays welcome information according to user name 
function Hello (_name) { 
 alert ("Hello," +_name); 
} 
Creates a function that returns a parameterless 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.

Four, correct understanding of Timer "timing" function

First look at a piece of code

function display () {
 alert (hello);
}
SetTimeout ("Display ()", 3000);
Alert ("The first thing you see is me!") ")

Which is the code to output first? The answer is obvious in the program. Why, then?

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

The following is a JavaScript thread, and the following figure represents the JavaScript process timeline.

In addition to the JavaScript execution process, there is also a code queue that needs to be executed at the next idle time of the process, and as the page progresses through its lifecycle, 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 it 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 the attention added to the queue does not mean that it will execute immediately, but only that it will execute as soon as possible, setting a timer that executes 250ms and does not mean that it will execute immediately after 250ms, It only means that it will be added to the queue after 250ms, and if the time queue is idle, then the code will be executed.

Please see the following code:

var btn = document.getElementById ("mybtn");
 Btn.onclick = function () {
 settimeout (function () {
 document.getElementById ("message"). NodeName = "Mymessage" ;
 other code
 };
 

The most notable thing about timers is that the specified interval indicates when the code for the timer is added to the queue, not when the code is executed. About this onclick business process timeline Please look at the following figure:

The above is the entire content of this article, hope that through this article we know more about the JavaScript timer, we common progress.

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.