JavaScript setInterval 和 setTimeout [英] JavaScript setInterval and setTimeout
问题描述
下一个代码每 1 秒显示一次日期,然后停止.
The next code display the date every 1 sec and then stops.
(function() {
var i = setInterval(function() {
console.log(new Date());
}, 1000);
console.log("Hi");
setTimeout(function() {
clearInterval(i);
}, 3000);
console.log("Hola");
})();
输出:
Hi
Hola
Wed Oct 24 2012 13:35:27 GMT+0200 (CEST)
Wed Oct 24 2012 13:35:28 GMT+0200 (CEST)
Wed Oct 24 2012 13:35:29 GMT+0200 (CEST)
但是不知道为什么先显示Hi
和Hola
.另外,为什么要执行 setTimeout
?不是假设 setInterval
每 1 秒执行一次而其他任何东西都不能执行吗?.(上面的代码是否按照编写的顺序运行?)谢谢.
But I don't know why Hi
and Hola
are displayed first. Also, why setTimeout
is executed? It is not supposed that setInterval
is executed every 1 sec and nothing else can be executed?. (Does the code above runs on the order in which it is written?)
Thanks.
推荐答案
setTimeout
以及 setInterval
只注册函数(回调),然后直接进入下一个命令.
setTimeout
as well as setInterval
only register functions (callbacks) but then go straight to the next command.
因此 Hi
和 Hola
在调用第一个回调之前打印.
Therefor Hi
and Hola
are printed before the first callbacks are called.
第一个回调将在 1 秒后是 setInterval
,然后在 2 秒后再次回调.3 秒后 setTimeout
启动并清除 setInterval
.
First callback will be that of setInterval
after 1 sec, then again after 2 sec.. After 3 seconds setTimeout
kicks in and clears setInterval
.
这篇关于JavaScript setInterval 和 setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!