On the use of setinterval and settimeout in JavaScript-basic knowledge

Source: Internet
Author: User
Tags setinterval

When it comes to setinterval, you have to mention settimeout, both of which are used to perform a function on a regular basis, the difference being that settimeout is executed only once, and setinterval can be executed continuously, typically as follows:

function Do_sth () {console.log (' Hello ... ');}

settimeout (Do_sth, 2500);  After 2.5 seconds, perform the Do_sth function (only once)
setinterval (do_sth, 3500);//3.5 seconds, execute the DO_STH function (execute once every 3.5 seconds, keep going)

On the surface, the two have their own uses, no problem. However, if the function performed by SetInterval is a time-consuming action, the setinterval will still call that function as planned, regardless of any previous blocking, so that the number of functions waiting to be executed in the queue will increase over time. The solution for this problem is still to use recursive calls to settimeout, such as:

function Do_sth () {
 console.log (' Hello ... ');  Even if the execution of the more time-consuming action is no problem,//
                  Wait here after the execution will be again to call settimeout

 settimeout (do_sth, 2500);//Schedule follow-up implementation
}

do_sth ();             //Initial implementation

This recursive invocation can not only achieve the purpose of looping through a function, but also prevent subsequent tasks from accumulating.

If you think this is a bit verbose, you can write a few more refinements:

(function () {
 console.log (' Hello ... ');  Do something here
 settimeout (Arguments.callee, 2500);
}) ();

To say so, but if the scheduled task cost is very small, setinterval is generally not a problem, but if the task is expensive, make sure to use settimeout.

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.