JavaScript timer, cancellation timer, and JS Timer optimization method

Source: Internet
Author: User
Tags setinterval

The usual method:

Start Timer:

[JavaScript]View PlainCopy 
    1. Window.setinterval (Method,time)

Method is a timed call to JS methods

Time is the interval, in milliseconds

Cancel Timer:

[JavaScript]View PlainCopy  
    1. Clearinterval (Method);



So here's the problem. With Clearinterval (Timerid), to clear, often can not stop immediately, with what method better solve?

The optimization scheme is as follows

[JavaScript]View PlainCopy 
    1. var timeout = false; //Start and Close button
    2. function Time ()
    3. {
    4. if (timeout) return;
    5. Method ();
    6. SetTimeout (time,100); //time refers to itself, the delay recursively calls itself, 100 is the interval call time, unit milliseconds
    7. }

Summarize
Generally do not setinterval, and use settimeout delay to return to replace interval.
SetInterval will generate callback stacks, especially when the time is short.

JavaScript timer, cancellation timer, and JS Timer optimization method

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.