我有两个使用 setTimeout() 的类似函数,但它给了我两个不同的结果 [重复]

I have two similar functions using setTimeout() but it is giving me two different results [duplicate]

提问人:reed richards 提问时间:10/24/2023 最后编辑:VLAZreed richards 更新时间:10/24/2023 访问量:50

问:

在函数调用 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
javascript 异步 settimeout 局部变量

评论

1赞 Yousaf 10/24/2023
With 的每个函数调用都会创建一个新变量。不会像 does 那样返回函数。 调用调用 返回的函数。所以 every 不会创建变量。call2timercall2myFunctioncall1myFunctioncall1timer

答:

0赞 Khoa 10/24/2023 #1

在 中,我们称之为“闭合”。“闭合”是你要找的关键词。call1

简而言之,它应该在完成后终止。但是,返回一个引用 .所以 没有终止。这种上下文称为“关闭”。timercall1call1timertimer

请注意,这是对所发生情况的快速概述。为了更好地理解,你可以谷歌专门的资源来解释 JavaScript 中的“闭包”是什么。

评论

0赞 reed richards 10/24/2023
谢谢你明白了