Setinterval timer latency

Source: Internet
Author: User
Timer latency

JS Timer

When setTimeout and setinterval functions are used, the time interval t set for the second parameter is from the time when this function (setTimeout (F1, T) and setinterval (F1, t) are called, after T ms, F1 is added to the UI task queue, but not necessarily executed, especially when other tasks are executed during this period, there may be a time delay. Therefore, when you use the setinterval function to create a timer, a delay occurs.

 
  1. var startTime = new Date().getTime();
  2. var count = 0;
  3. /*setInterval(function(){
  4. var i = 0;
  5. while(i++ < 100000000);
  6. }, 0);*/
  7. function fixed() {
  8. count++;
  9. var offset = new Date().getTime() - (startTime + count * 1000);
  10. var nextTime = 1000 - offset;
  11. if (nextTime < 0) nextTime = 0;
  12. SetTimeout (fixed, nexttime); // corrected the latency
  13. console.log(new Date().getTime() - (startTime + count * 1000));
  14. }
  15. setTimeout(fixed, 1000);

Setinterval timer latency

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.