setTimeout and setInterval
JavaScript setTimeout and setInterval (JavaScript setTimeout和setInterval)
JavaScript allows you not only to invoke the function right now but also a particular time later. The latter is known as a “scheduling call.” (JavaScript不仅允许您现在调用函数,还允许您在特定时间后调用函数。后者被称为“调度通话”。)
Two main methods can be highlighted for it:
setTimeout: calls a function once after a particularized delay. setInterval: calls a function repeatedly, beginning after some time, then repeating continuously at the given interval.
These methods are generally supported in all browsers, as well as Node.js. (所有浏览器以及Node.js通常都支持这些方法。)
setTimeout
setTimeout
For setTimeout this syntax is used:
let timerId = setTimeout(func | code, [delay], [arg1], [arg2], ...)
It has the following parameters:
func|code: a string or a function of code for executing. As a rule, it’s a function. A code string might be passed, but it’s not recommended.
delay: the before-running delay, in milliseconds, 0 by default.
arg1, arg2…: the function arguments ( IE9- doesn’t support them).
For example, the given code calls welcome() in a second, as follows:
function welcome() {
console.log('Welcome to w3cdoc');
}
setTimeout(welcome, 1000);
Along with the arguments:
function welcome(message, siteName) {
console.log(message + ' to ' + siteName);
}
setTimeout(welcome, 1000, "Welcome", "w3cdoc"); //Welcome to w3cdoc
In case the first argument turns out to be string, JavaScript makes a function from it:
setTimeout("console.log('Welcome to w3cdoc')", 1000);
But, it is recommended to use arrow functions and not strings. (但是,建议使用箭头函数而不是字符串。)
For instance:
setTimeout(() => console.log('Welcome to w3cdoc'), 1000);
We recommend to pass a function and not to run it. (我们建议传递一个函数,不要运行它。)
It’s not a good idea to add brackets () after the function. (在函数后添加括号()不是一个好主意。)
// wrong!
setTimeout(welcome(), 1000);
Cancel with clearTimeout
Cancel with clearTimeout (使用clearTimeout取消)
The setTimeout call returns a “timer-identifier” timerId used for canceling the invocation. (SetTimeout调用返回用于取消调用的“timer-identifier” timerId。)
The following syntax is used for canceling:
let timeoutId = setTimeout(...);
clearTimeout(timeoutId);
In the example given below, the function is scheduled and then called off:
let timeoutId = setTimeout(() => console.log("Hello, dear user!"), 2000);
console.log(timeoutId); // timer identifier
clearTimeout(timeoutId);
console.log(timeoutId); // same identifier (doesn't become null after canceling)
The alert output shows that the time identifier of the browser represents a number. The result can be different in other environments. So, there isn’t any common specification for the methods. (Alert输出显示浏览器的时间标识符代表一个数字。在其他环境中,结果可能有所不同。因此,这些方法没有任何通用规范。)
setInterval
setInterval
The syntax of the setInterval is the same as for the setTimeout:
let timerId = setInterval(func | code, [delay], [arg1], [arg2], ...)
The meaning is the same for all the arguments. But, unlike the setTimeout method, it invokes the function regularly after a particular interval of time. (所有参数的含义都是一样的。但是,与setTimeout方法不同,它会在特定的时间间隔后定期调用函数。)
Call clearInterval(timerId) for stopping upcoming calls. (调用clearInterval (timerId)以停止即将到来的调用。)
Let’s check out an example:
// repeat with the interval of 2 seconds
let intervalTimerId = setInterval(() => console.log('start'), 2000);
// after 5 seconds stop
setTimeout(() => {
clearInterval(intervalTimerId);
console.log('stop');
}, 5000);
Nested setTimeout
Nested setTimeout (嵌套setTimeout)
We can highlight two major ways to run something regularly. The first is setInterval, the second one is setTimeout, like here:
/** instead of:
let intervalTimerId = setInterval(() => console.log('start'), 1000);
*/
let intervalTimerId = setTimeout(function start() {
console.log('start');
intervalTimerId = setTimeout(start, 1000); // (*)
}, 1000);
The setTimeout schedules the upcoming call at the end of the current one (). (SetTimeout在当前调用()结束时安排即将到来的调用。)
The nested setTimeout method is more flexible than setInterval. For example, you want to write a service for sending a request to the server once in 5 seconds to ask for data. If the server is busy, the interval will be increased to 10, 20, 40 seconds, and more. (嵌套的setTimeout方法比setInterval更灵活。例如,您希望编写一个服务,用于在5秒内向服务器发送一次请求以请求数据。如果服务器繁忙,间隔将增加到10、20、40秒等。)
For instance:
let delay = 3000;
let intervalTimerId = setTimeout(function request() {
//send request
(发送请求)
if (the request failed as the server was overloaded) {
delay *= 2;
}
intervalTimerId = setTimeout(request, delay);
}, delay);
Consider that nested setTimeout can help you to set the delay between the invocations more accurately than setInterval. (考虑嵌套的setTimeout可以帮助您比setInterval更准确地设置调用之间的延迟。)
Let’s correlate two code fragments. The setInterval is used by the first one:
let i = 1;
setInterval(function () {
f(i++);
}, 1000);
The second code uses the nested setTimeout:
let i = 1;
setTimeout(function run() {
f(i++);
setTimeout(run, 100);
}, 100);
As for the setInterval the internal scheduler runs f(i++) every 100 milliseconds (ms). (至于setInterval ,内部调度程序每100毫秒(ms)运行一次f (i + +)。)
The real delay between f calls for setInterval is shorter than inside the code. (SetInterval的f调用之间的实际延迟比代码内部短。)
Now, let’s check out the picture of the nested setTimeout:
The nested setTimeout ensures a fixed delay. The reason is that it plans a new call after the previous call. (嵌套的setTimeout确保了固定的延迟。原因是它计划在上一次通话后进行新的通话。)
Zero Delay setTimeout
Zero Delay setTimeout (零延迟setTimeout)
There exists a unique use case: setTimeout(f, 0), or setTimeout(f) scheduling the execution of f. It schedules the function to run right after the current script.
For instance:
setTimeout(() => console.log("w3cdoc"));
console.log("Welcome to");
Browsers set limitations on how often nested timers may run. The HTML5 standard states that after five nested timers, the interval must be at least 4 ms. (浏览器对嵌套计时器的运行频率设置了限制。HTML5标准规定,在五个嵌套计时器之后,间隔必须至少为4毫秒。)
server-side JavaScript, there are no such limitations. It offers other ways of scheduling an immediate asynchronous job, such as setImmediate for Node.js. (服务器端的JavaScript ,没有这样的限制。它提供了其他安排即时异步作业的方法,例如Node.js的setImmediate。)