JavaScript Timer Learning Notes

Source: Internet
Author: User

Mastering the timer principle must be known: theJavaScript engine is single-threaded, the browser whenever only and only one thread is running the JavaScript program. as the saying goes: SetTimeout and setinterval are pseudo-threads.

JavaScript is run in a single-threaded environment, and during the declaration cycle of a page there may be other code that controls the JavaScript process, such as the code contained in the <script> element, the event handler for the DOM element, and the Ajax callback function. The timer simply adds code to the code queue at some point in the future, and execution timing is not guaranteed. Code queuing runs the code in the queue to the main thread after the main process is idle, following the FIFO-first principle.

  

The JavaScript master process is in a different state at different times, starting with the code in the <script> element in the page, and when the initial load is complete, the main process enters an idle state, when the DOM element produces the Click event, and the event-handling code is added to the code queue. The code queue discovers that the JavaScript master process is idle and immediately hands the first element in the queue to the main process execution. is the timeline for this process.

no code in JavaScript is carried out immediately, with the execution as soon as the process is idle. For example, when a button is pressed, the event handler is added to the code queue. When an AJAX response is received, the code for the back-up function is added to the queue. the timer works on the queue by adding code to the queue when a particular event has passed. Setting a timer that executes after 150ms does not mean that the code executes after 150ms, but that the code is added to the code queue after 150ms. When the main process is idle and the element is at the top of the queue, the code executes immediately, seemingly at a precise point in time. In fact, all the code in the queue waits until the main process is idle before executing, regardless of how they are added to the queue.

var ele = document.getElementById (' btn 'function() {    setTimeout (  function() {        = "Red";     255);     var start = date.now ();      while (Date.now ()-Start <) {};}

In the example above, the timer is inserted into the code queue in 255ms, but the JavaScript main thread has 300ms running, then the timer code will be executed at least after 300ms after the timer is set. The following timeline represents the execution of the above code.

  

  Repeat Timer setinterval

To ensure that the timer code is inserted into the queue, the total minimum interval is the specified time. When using SetInterval (), the timer code can be added to the code queue only if no other code instance of the timer is available. Assuming there is no such principle, the timer created by SetInterval () ensures that the timer code can be inserted into the queue in a regular way. So the problem is, assuming that the JavaScript main process is running for a long time, then the SetInterval code is added to the code queue multiple times, and the timer code executes multiple times without any pauses until the main process is idle.

But this rule also brings two questions:

    1. Some of the intervals will be skipped.
    2. The interval between the code execution of multiple timers may be smaller than expected
 var  ele = document.getElementById (' btn ' ); Ele.onclick  = function   () {setinterval ( /span>function   () {
Console.log (' Run Interval '); var start = Date.now (); while (Date.now ()-Start < 350 200); var start = Date.now (); while (Date.now ()-Start < 300

In the above code, the click event handler sets a 200ms time interval for a repeating timer through setinterval. From the above code can be seen that the event handler took more than 300ms time to complete, and the timer code also took 300ms of time, this time there will be skipping interval and run the timer code two times in a row. Please see:

  

, the first timer is added to the queue in 205ms, but it is not able to execute until it is over 300ms. When the timer code is executed, a timer code instance is added to the wait queue at 405ms. At 605MS, the first timer code is still running, and a code instance of another timer is already in the code queue. So the timer code at this point in time will not be added to the queue. Results when the timer code added at 205MS is finished, the timer code added at 405MS is executed immediately.

So there are two issues to be aware of when animating with SetInterval:

    1. Do not use fixed step as animation, be sure to use percent: Start value + (target value-start value) * (Date.now ()-Start time)/time interval
    2. If the main process is running too long, there is a phenomenon of skipping frames

To avoid the two drawbacks of setinterval, you can use the chain settimeout ():

SetTimeout (function() {    /// Other processing     setTimeout (Arguments.callee, interval);}, interval);

the above article is mainly from "JavaScript advanced Programming"

JavaScript Timer Learning Notes

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.