Learn the javascript timer _ javascript skills

Source: Internet
Author: User
I want to learn about the javascript timer, tell you how to use it, and propose a message request to you to create a timer. Are you interested in it? I. Timer Overview

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 a function name is used as the call handle, it cannot contain any parameters. When a string is used, 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. The following describes two methods.

SetInterval is similar to setTimeout. 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.

II. Specific Use

1. window. setTimeout Method

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

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

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:

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

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. To cancel scheduled execution, call the window. clearInterval method, similar to the clearTimeout method. The clearInterval method also receives the value returned by a setInterval method as a parameter. For example:

// Define a call for repeated invocation var id = window. setInterval ("somefunction", 10000); // cancel the scheduled execution of window. clearInterval (id );

3. Challenges

The above code is only used to describe how to cancel a scheduled execution. In fact, the setInterval method is used in many occasions. The following is a question for everyone:Design a stopwatch,To introduceSetInterval FunctionPurpose: The stopwatch will contain two buttons and a text box for displaying the time. When you click the start button, the timer starts. The minimum unit is 0.01 seconds. click the button again to stop the timer, the text box shows the elapsed time. Another button is used to clear the current time.Let's get started first. In the next article, we will reveal the answer. Click here to view the answer: javascript simple stopwatch timer.

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

Var userName = "jack"; // display the welcome information according to the user name function hello (_ name) {alert ("hello," + _ name) ;}// create a function, returns a non-Parameter 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.

4. Correctly Understand the timer function

First look at a piece of code

Function display () {alert (hello);} setTimeout ("display ()", 3000); alert ("the first thing you see is me! ")

Which code outputs first? The answer is obvious in the program. Why?

Beginners may have misunderstandings about the Javascript timers. They think they are threads. In fact, Javascript is running in a single thread, and the timer is only intended to be executed at a certain time in the future, the specific execution time cannot be guaranteed, because in the lifecycle of the page, other code may be in the process of controlling Javascript at different times. The browser is only responsible for sorting and assigns a code to run at a certain time point.

The following describes the Javascript thread, indicating the javascript process timeline.

In addition to the javascript Execution Process, there is also a code queue that needs to be executed in the next idle time of the process. As the page passes through its lifecycle, the code is added to the peer column in the execution order. For example, when a button is pressed, event processing is added to the queue and executed within the next possible time.

The timer works on the queue. When the specified time passes, the code is inserted. Note that adding to the queue does not mean that it will be executed immediately, but can only be said that it will be executed as soon as possible, set a timer to be executed after Ms. It does not mean that the timer will be executed immediately after Ms. It only means that the timer will be added to the queue after Ms. If the queue is idle at this time point, the code will be executed.

See the following code:

Var btn = document. getElementById ("mybtn"); btn. onclick = function () {setTimeout (function () {document. getElementById ("message "). nodeName = "mymessage"; // other codes}, 250 );}

Note that the specified time interval indicates when the timer code is added to the queue, rather than when the code is executed. For details about the process timeline processed by the onclick operator, refer:

The above is all the content of this article. We hope that you can better understand the javascript timer and make common progress through this article.

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.