如何让JavaScript等待某些事件发生? [英] How to let JavaScript wait until certain event happens?

查看:697
本文介绍了如何让JavaScript等待某些事件发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个具有以下结构的网页:

I am writing a webpage with the following structure:


  1. 一部分(表A)取决于另一部分(表B);

  2. 另一个部分(表B)具有每个更新需要重新计算的元素。计算由外部工具处理,并将在完成后导致事件。

为了保证正确性,表需要只有在其他表完全更新(即通过计算完成)后更新。但是,我不知道如何有效地实现这一点,我在JavaScript中找不到任何等待设施。

In order to guarantee correctness, the table need to be updated only after the other table is fully updated (i.e., done with computation). However, I don't know how to effectively achieve this, and I could not find any wait facility within JavaScript.

现在,我使用以下方法:

For now, I am using the following method:


  1. 声明全局变量已更新并使它 false ;

  2. 在第一个表接收到输入后,我做一个空的循环直到更新 true ;

  3. 添加一个听众,一旦计算完成并收到事件,将更新 true

  1. Declare a global variable updated and make it false;
  2. After the first table received input, I make an empty while loop until updated is true;
  3. Add an listener, once the calculation is done and the event received, set updated to true.

这似乎不直观,但我不能想到任何其他方式。有没有什么好的方法呢?

This seems unintuitive to me but I cannot think of any other way of doing it. Is there any good ways to do this?

感谢任何输入!

推荐答案


添加一个监听器,一旦计算完成并收到事件,将更新设置为true。

Add an listener, once the calculation is done and the event received, set updated to true.

而不是将更新设置为true,然后等待更新成为true - 只要做任何你想要的在听众中做。

Instead of setting updated to true, and then waiting for updated to be true- just do whatever you want to do in the listener.

myEventBus.addListener(function () {
    // do whatever
    updateTable();
    alert('table updated!');
});

这篇关于如何让JavaScript等待某些事件发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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