JavaScript:暂停函数并等待全局变量 [英] JavaScript: Pause a function and wait on a global variable

查看:44
本文介绍了JavaScript:暂停函数并等待全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个全局变量 window.listNodes ,它是一个数组.该变量每3秒刷新一次,并依次填充.

There is a global variable window.listNodes that is an array. This variable is refreshed each 3 seconds and is filled sequentially.

另一个函数 onOpen()由用户触发,需要具有包含3个元素(不少于3个元素)的全局变量 window.listNodes .我要做什么:如果全局变量的 .length 不等于3,则程序等待代码的另一部分填充 window.listNodes ,然后开始再次是功能 onOpen().

Another function onOpen() is triggered by the user and needs to have the global variable window.listNodes containing 3 elements, not less. What I seek to do: if the global variable has not a .length equal to 3 then the program waits that the other part of the code fills window.listNodes and then begin again the function onOpen().

socket.onopen = function onOpen() {
        if (window.listNodes.length === 3) {
            // Do something
        } else {
            // Wait and when window.listNodes.length === 3:
            onOpen(); 
        }
    });
};

有一种简单的方法吗?我尝试使用函数 setTimeOut()和生成器函数以及关键字 yield ,但是失败了.

Is there an easy way to do it? I tried with the function setTimeOut() and with a generator function and the keyword yield but I failed.

感谢您的宝贵帮助:)

Thank you for your precious help :)

推荐答案

这可以使用 setTimeout 和自定义间隔来等待,例如500ms,以执行此操作:

This could use setTimeout and a custom interval to wait, for example, 500ms, to do it:

function onOpen() {
        if (window.listNodes.length === 3) {
            // Do something
        } else {
            // Wait and when window.listNodes.length === 3:
            setTimeout(onOpen, 500);
        }
    });
};

socket.onopen = onOpen;

这篇关于JavaScript:暂停函数并等待全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆