How to let JavaScript wait until certain event happens?

旧城冷巷雨未停 提交于 2019-12-23 07:46:28

问题


I am writing a webpage with the following structure:

  1. One section (table A) depends on another section (table B);
  2. Another section (table B) has elements that require recalculation on each update. The calculation is handled by external tools, and will cause an event when finished.

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. 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?

Thanks for any inputs!


回答1:


Add an listener, once the calculation is done and the event received, set updated to 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!');
});



回答2:


Doing empty while loops is a bad idea. Not only do you burn CPU cycles, but Javacript is single threaded so you will loop forever without giving anyone a chance to change the variable.

What you can do is rewrite the table that has other people depending on it to "fire an event itself". There are many ways to do this, but basicaly you just want it to call a "continuation' function instead of blindily returning. This function can be predefined or you can pass it as a parameter somewhere.

//this is just illustrative
//Your actual code will be probably very different from this.

function update_part(){
    //do something
    signal_finished_part()
}

var parts_done = 0;
function signal_finished_part(){
    parts_done ++;
    if(parts_done >= 5){
        signal_all_parts_done();
    }
}

function signal_all_parts_done()
{
    //do something to table A
}



回答3:


You could write a callback function for whatever triggers the update. To avoid messy callbacks, you could use promises too, and update parts of the table depending on the data retrieved in the update operation. Open to suggestions.



来源:https://stackoverflow.com/questions/6902334/how-to-let-javascript-wait-until-certain-event-happens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!