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

标签 javascript asynchronous google-closure-library

我有一个类 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/

相关文章:

javascript - 使用 d3 访问单个区域元素

javascript - 有没有办法读取dojo Objectstore并将其转换为JS数组对象

javascript - 单击动态生成的 anchor 标记时获取超链接文本

wcf - 如何正确等待WCF异步

javascript - 为 Google Closure 类定义属性的首选方法是什么?

javascript - 使用 Ember CLI 递归渲染 Handlebars 模板

ios - F# 异步 lambda 声明

c# - 我需要 MemoryBarrier 和 ReaderWriterLockSlim 吗?

google-closure - 谷歌关闭 - goog.require 找不到 goog.ui.AutoComplete

timer - 如何让 goog.Timer 更精确?