异步延迟JS直到满足条件

编程入门 行业动态 更新时间:2024-10-22 13:27:30
本文介绍了异步延迟JS直到满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have a class, ChatRoom, that can only render after it receives a long-running HTTP request (it could take 1 second or 30 seconds). So I need to delay rendering until ChatRoom.json is not null.

在下面的代码中,我正在使用Closure Library的 goog.async.ConditionalDelay .它可以工作,但是有更好的方法(也许不需要闭包库)来做到这一点吗?

In the code below, I'm using Closure Library's goog.async.ConditionalDelay. It works, but is there a better way (maybe without needing Closure Library) to do this?

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执行).

Note that "while (json == null) { }" isn't possible because that would be synchronous (blocking all other JS execution).

推荐答案

请考虑以下问题:

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

这将每半秒检查一次.

实时演示: jsfiddle/kBgTx/

更多推荐

异步延迟JS直到满足条件

本文发布于:2023-11-27 09:23:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637491.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条件   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!