JavaScript timer and optimized cancel timer method, javascript Timer

Source: Internet
Author: User

JavaScript timer and optimized cancel timer method, javascript Timer

Common Methods:
Start Timer:
Copy codeThe Code is as follows:
Window. setInterval (Method, Time)

Method is the js Method that is periodically called.

Time is the interval, in milliseconds
Cancel Timer:
Copy codeThe Code is as follows:
ClearInterval (Method );

The problem arises. ClearInterval (timerid); is used to clear data, and usually cannot be stopped immediately. How can this problem be solved?
The optimization scheme is as follows:
Copy codeThe Code is as follows:
Var timeout = false; // the start and close buttons.
Function time ()
{
If (timeout) return;
Method ();
SetTimeout (time, 100); // time refers to itself, which is a recursive call of its own delay. 100 indicates the call interval, in milliseconds.
}

Summary

Generally, setInterval is not used, and the interval recursion of setTimeout is used instead of interval.
SetInterval will generate callback accumulation, especially when the time is short.

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.