gpt4 book ai didi

javascript - 传递给 setInterval 的函数范围

转载 作者:行者123 更新时间:2023-11-30 08:24:18 24 4
gpt4 key购买 nike

在 setInterval 中调用时,我无法理解函数作用域。

当我像这样在 setInterval 中直接声明一个匿名函数时:

let lastEventUUID = "some ID";
const interval = setInterval(async function() {
console.log("lastEventUUID -> " + lastEventUUID);
lastEventUUID = "another ID";
}, 1000);

一切都按预期工作,我明白了

lastEventUUID -> some ID
lastEventUUID -> another ID
...

但是当我单独声明我的函数时

async function myFunc(lastEventUUID) {
console.log("lastEventUUID -> " + lastEventUUID);
lastEventUUID = "another ID";
}

然后在 setInterval 中调用设置它:

let lastEventUUID = "some ID";
const interval = setInterval(myFunc, 1000, lastEventUUID);

lastEventUUID 没有在下一次调用中更新,我得到

lastEventUUID -> some ID
lastEventUUID -> some ID
...

我在这里错过了什么?

最佳答案

与是否单独定义函数无关。在您的第一个示例中,您正在使用函数关闭的 lastEventID 变量。在第二个示例中,您使用的是传递给函数的 lastEventID parameter。由于 setInterval 每次都传递相同的值,因此您每次都会看到相同的值。

如果做like-for-like,可以单独定义:

async function myFunc() {
// ^----- No parameter declared
console.log("lastEventUUID -> " + lastEventUUID);
lastEventUUID = "another ID";
}
let lastEventUUID = "some ID";
const interval = setInterval(myFunc, 1000);
// No argument given to pass to myFunc --^


旁注:您已将函数定义为 async function .如果您的实际功能正在使用 await在函数主体中,确保在函数的完整 主体周围有一个try/catch 并处理任何错误;否则,错误将导致“未处理的拒绝”错误(因为计时器机制不会对您的函数返回的 promise 做任何事情,包括处理拒绝)。如果您的真实函数不使用 await,则没有理由将其设为 async


回复你的评论:

From what I understand this work because here lastEventUUID is declared in the global scope, but in my case, it is defined in another function...

不,它不起作用,因为它是全局的。它之所以有效,是因为它是在函数定义的范围或父范围中声明的。如果那是函数的范围,它就可以正常工作。示例:

function foo() {
async function myFunc() {
console.log("lastEventUUID -> " + lastEventUUID);
lastEventUUID = "another ID";
}
let lastEventUUID = "some ID";
const interval = setInterval(myFunc, 1000);
}
foo();

全局变量只是这个概念的一个极端例子,它被称为闭包。更多:How do JavaScript closures work?

事实上,如果我们调用该函数两次,我们会看到它们中的每个 都有一个lastEventID 变量(对于foo):

function foo(x) {
async function myFunc() {
console.log("x -> " + x + ", lastEventUUID -> " + lastEventUUID);
lastEventUUID = "another ID";
}
let lastEventUUID = "some ID";
const interval = setInterval(myFunc, 1000);
}
foo(1);
foo(2);

关于javascript - 传递给 setInterval 的函数范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48096435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com