How JavaScript Timers work

Source: Internet
Author: User

The delay time set by the timer is not guaranteed. Because all JavaScript single-threaded asynchronous events (such as mouse click events and timers) executed in the browser are only executed when it is empty.

SetTimeout will need at least a delay of 10ms after each callback function execution (perhaps more, but not less). But SetInterval will try to execute the callback function every 10ms, regardless of whether the previous callback function is still executing.

  • The JavaScript engine has only one thread, forcing an asynchronous event to be added to the queue to wait for execution.
  • There is an essential difference between setTimeout and setinterval when executing asynchronous code.
  • If the timer is blocked by the code being executed, it will go to the end of the queue to wait until the next possible time to execute (possibly exceeding the delay time it has set).
  • If the interval callback function takes a long time to execute (longer than the specified delay), interval may have no delay and execute the callback function back-to-back.

var num = 12;
Console.log (num);
SetTimeout (function () {
num++;
Console.log (num);
},0);

for (Var i=0;i<1000000;i++) {
Code
}
Console.log (num);

Because the time for the for loop has exceeded the timer's wait time. Therefore, the callback function inside the timer can only wait until after the execution of the following code has been completed. Because even if the timer delays write 0, it will still have a default delay time, and the delay time of each browser is different.

How JavaScript Timers work

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.