[英]setTimeout in the same function to whom it is calling?
I have learned that the setTimeout function runs once and the setInterval runs continuously after the specified time but when I am calling the setTimeout function in the same function it is calling it is behaving like the setInterval but when I am doing setInterval instead of set timeout it行为怪异。 谁能告诉我 function 中的 setTimeout 和 setInetval 发生了什么?
带有 setTimeout 的代码
function hello(){ console.log("hello"); setTimeout(hello,2000) } hello()
function hello(){ console.log("hello"); setInterval(hello,2000) } hello()
提前致谢
setTimeout
允许我们运行一次 function。setInterval
允许我们重复运行 function。 在您的示例中,只有一个setTimout
始终存在,但setInterval
每 2000 毫秒创建一个。
在第一个示例中:每当调用hello
方法时,它都会注册一个新计时器以在 2000 毫秒后调用 hello。 因此,2000 毫秒后总会有一次调用。
在第二个示例中:每当调用 hello 时,它每次都会注册一个新的setInterval
而不会终止先前的setInterval
,这将导致每次都注册新的setInterval
,并且您将在控制台上获得多个日志,每次调用hello
时都会不断增加。
不同的是,当function中有setTimeout时,每次执行ZC1C425268E68385D1AB5074F14ZA后,异步调用栈都会在异步调用栈中添加一个新的function要执行。 虽然setinterval还在异步调用栈中增加了一个要执行的function,但是当前添加的要执行的function中包含了一个setinterval,意思是setinterval执行的时候会有一个指数数。
可以执行以下代码方便理解:
let count = 0 function hello() { console.log("hello"); console.log("count:" + count++); setInterval(hello, 2000) } hello()
在setInterval
中,您的 function 将根据您的代码每 2 秒调用一次。
function hello(){
console.log("hello");
setInterval(hello,2000)
}
hello()
这里调用了Hello()
。 2 秒后再次用另一个 setInterval() 调用 hello。 它将再次调用 hello method()。 虽然 javascript 是asynchronous
的,但它会在一段时间后调用数千个hello()
。 所以这不是写 setInterval 的正确方法。
你可以这样写。
function hello() {
console.log("hello");
}
setInterval(hello, 2000)
现在 setInterval 将每 2 秒调用一次。
下方评论,如有疑问
根据您的评论,我将尝试简要描述异步。
function methodOne() {
setTimeout(function () {
console.log("method one called");
}, 5000)
}
function methodTwo() {
setTimeout(function () {
console.log("method two called");
}, 2000)
}
methodOne()
methodTwo()
现在 methodOne( methodOne()
需要 5 秒, methodTwo()
需要 2 秒。 两者都需要 5 秒。 让我们看看如何:第一个methodOne()
被调用。 Javascript 不会等待 methodOne() 的执行完成。 它将移至methodTwo()
。 MethodTwo()
将在 2 秒内执行。 MethodOne()
仍在处理中。 3秒后; 表示在 5 秒内完成methodOne()
将完成执行。
所以这两个函数不会互相等待。 它异步执行。
希望这会让你明白。 如果您有任何疑问,请在下方评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.