Amy*_*y B 9 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);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,"while(json == null){}"是不可能的,因为这将是同步的(阻止所有其他JS执行).
Šim*_*das 24
考虑一下:
(function wait() {
if ( chatroom.json ) {
chatroom.render();
} else {
setTimeout( wait, 500 );
}
})();
Run Code Online (Sandbox Code Playgroud)
这将每半秒检查一次.
现场演示: http ://jsfiddle.net/kBgTx/
| 归档时间: |
|
| 查看次数: |
11798 次 |
| 最近记录: |