gpt4 book ai didi

javascript - 在同一函数中调用 `Function` 与 `Function()`

转载 作者:行者123 更新时间:2023-11-28 12:20:19 25 4
gpt4 key购买 nike

我正在编写一个很长的轮询脚本,并遇到了太多递归错误,导致浏览器挂起。我的目标是使用 setTimeout() 每 1000 毫秒调用相同的函数。是的,我可以使用 setInterval() 但它将是一个很长的轮询脚本,并且将等待服务器响应。

我通过从同一函数中调用的函数中删除 () 解决了这个问题。

我的脚本如下所示:

function messagePolling(){
console.log("polled")
setTimeout(messagePolling(),1000) // <--- removing `()` from the function works as intended
}

messagePolling();

这背后的逻辑是什么? messagePolling 毕竟是一个函数,不是吗。

最佳答案

你说得完全正确 - messagePolling 是一个函数。但是,messagePolling() 不是一个函数。您可以在控制台中看到这一点:

// assume messagePolling is a function that doesn't return anything
messagePolling() // -> undefined

所以,当你这样做时:

setTimeout(messagePolling(), 1000)

你确实在这样做:

setTimeout(undefined, 1000)

但是当你这样做时:

setTimeout(messagePolling, 1000)

实际上是将函数传递给setTimeout。然后 setTimeout 将知道稍后运行您传递的函数 - messagePolling。如果稍后决定调用 undefined (messagePolling() 的结果),它就不起作用,对吧?

关于javascript - 在同一函数中调用 `Function` 与 `Function()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39679938/

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