gpt4 book ai didi

Javascript 轮询服务器。这会导致堆栈溢出吗?

转载 作者:行者123 更新时间:2023-11-29 10:55:01 24 4
gpt4 key购买 nike

我不太熟悉每个浏览器上每个 javascript 实现的细节。但是我知道使用 setTimeout,传入的方法在单独的线程上被调用。那么在方法内部递归地使用 setTimeout 会导致其堆栈无限增长直到导致堆栈溢出吗?还是它会创建一个单独的调用堆栈并在失去焦点后销毁当前帧?这是我想知道的代码。

function pollServer()
{
$.getJSON("poll.php", {}, function(data){
window.setTimeout(pollServer, 1000);
});
}

window.setTimeout(pollServer, 0);

我想每隔一秒左右轮询一次服务器,但不想用“阻塞循环”浪费 CPU 周期 - 我也不想设置时间限制来限制用户在访问页面之前可以访问页面的时间浏览器死机。

编辑

使用 firebug,我设置了几个断点,通过查看“脚本 -> 堆栈”面板,我发现调用堆栈实际上只是“pollServer”,并且不会在每次调用时增长。这很好 - 但是,JS 的任何其他实现是否有不同的行为?

最佳答案

我不确定它是否会造成堆栈溢出,但我建议您在周期不变的情况下使用 setInterval

这就是prototype实现其 PeriodicalExecuter

// Taken from Prototype (www.prototypejs.org)
var PeriodicalExecuter = Class.create({
initialize: function(callback, frequency) {
this.callback = callback;
this.frequency = frequency;
this.currentlyExecuting = false;

this.registerCallback();
},

registerCallback: function() {
this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
},

execute: function() {
this.callback(this);
},

stop: function() {
if (!this.timer) return;
clearInterval(this.timer);
this.timer = null;
},

onTimerEvent: function() {
if (!this.currentlyExecuting) {
try {
this.currentlyExecuting = true;
this.execute();
} finally {
this.currentlyExecuting = false;
}
}
}
});

关于Javascript 轮询服务器。这会导致堆栈溢出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1155245/

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