Home >Web Front-end >JS Tutorial >A brief discussion on the use of setInterval and setTimeout in JavaScript_Basic knowledge

A brief discussion on the use of setInterval and setTimeout in JavaScript_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:47:371406browse

When it comes to setInterval, we have to mention setTimeout. Both are used to execute a certain function regularly. The difference is that setTimeout is only executed once, while setInterval can be executed continuously. Typical usage is as follows:

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

setTimeout(do_sth, 2500);  // 2.5 秒后,执行 do_sth 函数(只执行一次)
setInterval(do_sth, 3500); // 3.5 秒后,执行 do_sth 函数(每隔 3.5 秒执行一次,一直执行下去)

On the surface, both have their own uses and there is no problem. However, if the function executed by setInterval is a time-consuming action, setInterval will still call that function according to the original plan, regardless of any previous blocking. In this way, as time goes by, the number of functions waiting to be executed in the queue will increase. The more. The solution to this problem is still to recursively call setTimeout, such as:

function do_sth() {
 console.log('Hello...');  // 即使这里执行比较耗时的动作也没问题,
                  // 等这里执行完了才会再去调用 setTimeout

 setTimeout(do_sth, 2500); // 安排后续执行
}

do_sth();             // 初次执行

This recursive calling method can not only achieve the purpose of executing a certain function in a loop, but also prevent subsequent tasks from accumulating.

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

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

That’s it, but if the task cost of scheduled execution is small, setInterval is generally no problem, but if the task cost is relatively high, be sure to use setTimeout.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn