gpt4 book ai didi

javascript - 异步延迟 JS 直到满足条件

转载 作者:数据小太阳 更新时间:2023-10-29 04:24:30 25 4
gpt4 key购买 nike

我有一个类 ChatRoom,它只能在收到长时间运行的 HTTP 请求(可能需要 1 秒或 30 秒)后呈现。所以我需要延迟渲染,直到 ChatRoom.json 不为空。

在下面的代码中,我使用了 Closure Library 的 goog.async.ConditionalDelay .它有效,但是否有更好的方法(也许不需要 Closure Library)来做到这一点?

ChatRoom.prototype.json = null; // received after a long-running HTTP request.

ChatRoom.prototype.render = function() {
var thisChatRoom = this;

function onReady() {
console.log("Received JSON", thisChatRoom.json);
// Do rendering...
}

function onFailure() {
alert('Sorry, an error occurred. The chat room couldn\'t open');
}

function isReady() {
if (thisChatRoom.json != null) {
return true;
}
console.log("Waiting for chat room JSON...");
return false;
}

// If there is a JSON request in progress, wait until it completes.
if (isReady()) {
onReady();
} else {
var delay = new goog.async.ConditionalDelay(isReady);
delay.onSuccess = onReady;
delay.onFailure = onFailure;
delay.start(500, 5000);
}
}

请注意,“while (json == null) { }”是不可能的,因为那将是同步的(阻止所有其他 JS 执行)。

最佳答案

考虑一下:

(function wait() {
if ( chatroom.json ) {
chatroom.render();
} else {
setTimeout( wait, 500 );
}
})();

这将每半秒检查一次。

现场演示: http://jsfiddle.net/kBgTx/

关于javascript - 异步延迟 JS 直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7559386/

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