About the use of setInterval and setTimeout in JavaScript, settimeinterval

Source: Internet
Author: User

About the use of setInterval and setTimeout in JavaScript, settimeinterval

When it comes to setInterval, we have to mention setTimeout, both of which are used to regularly execute a function. The difference is that setTimeout is only executed once, And setInterval can be continuously executed. The typical usage is as follows:

function do_sth() { console.log('Hello...'); }
SetTimeout (do_something, 2500); // After 2.5 seconds, execute the do_something function (only once) setInterval (do_something, 3500); // After 3.5 seconds, execute the do_something function (execute every 3.5 seconds and keep running)

On the surface, the two have their own purposes and there is no problem. However, if the setInterval function is a time-consuming action, setInterval still calls the function according to the original plan without considering any previous blocking. As a result, over time, more and more functions are waiting for execution in the queue. The solution to this problem is still to call setTimeout recursively, for example:

Function do_something () {console. log ('Hello... '); // It is okay even if the time-consuming action is executed here. // the setTimeout (do_something, 2500) will be called after the execution is completed ); // schedule subsequent execution} do_something (); // initial execution

This method of recursive calling can achieve the purpose of executing a function cyclically and prevent subsequent tasks from accumulating.

If you think this method is a bit wordy, you can write it more refined:

(function() { console.log('Hello...');  // do something here setTimeout(arguments.callee, 2500);})();

In this case, if the scheduled execution task overhead is very small, setInterval is normal. However, if the task overhead is large, 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.