提问人:reed richards 提问时间:10/24/2023 最后编辑:VLAZreed richards 更新时间:10/24/2023 访问量:50
我有两个使用 setTimeout() 的类似函数,但它给了我两个不同的结果 [重复]
I have two similar functions using setTimeout() but it is giving me two different results [duplicate]
问:
在函数调用 call1 和 call2 中,我试图实现相同的目的,即以 1000 秒的延迟打印值。但是我注意到的是,在 call1() 中,变量计时器在不同的函数调用之间仍然存在,而在 call2 中,当第二次调用 call2 时,第一次调用中的变量计时器不存在。为什么会这样?如果您为我提供一些资源,以便我了解这一点,那将会很有帮助 法典:
const myFunction= (d) => {
let timer ;
return function(){
if (timer) console.log("funCall1 : timer is still present");else console.log("funCall1 : timer not present")
timer = setTimeout(()=>{
console.log("funCall1 : inside setTimeout")
},d)
}
}
const call1=myFunction(1000)
function call2(){
let timer;
if(timer)
console.log("funCall2 : timer is present")
timer = setTimeout(()=>{
console.log("funCall2 : abc")
},1000)
}
call1()
call1()
call1()
call2()
call2()
call2()
我使用在线编译器programiz:JSCompiler编译了上面的代码
输出
funCall1 : timer not present
funCall1 : timer is still present
funCall1 : timer is still present
funCall1 : inside setTimeout
funCall1 : inside setTimeout
funCall1 : inside setTimeout
funCall2 : abc
funCall2 : abc
funCall2 : abc
答:
0赞
Khoa
10/24/2023
#1
在 中,我们称之为“闭合”。“闭合”是你要找的关键词。call1
简而言之,它应该在完成后终止。但是,返回一个引用 .所以 没有终止。这种上下文称为“关闭”。timer
call1
call1
timer
timer
请注意,这是对所发生情况的快速概述。为了更好地理解,你可以谷歌专门的资源来解释 JavaScript 中的“闭包”是什么。
评论
0赞
reed richards
10/24/2023
谢谢你明白了
评论
call2
timer
call2
myFunction
call1
myFunction
call1
timer