How to allow JavaScript to wait for a specific event to happen?

I am writing a web page with the following structure:

  • One section (table A) depends on another section (table B);
  • In another section (table B) there are elements that require recounting for each update. The calculation is performed by external tools and will lead to the completion of the event.

To ensure correctness, the table needs to be updated only after the other table has been completely updated (i.e. performed with the calculation). However, I do not know how to achieve this efficiently, and I could not find the wait object in JavaScript.

I am currently using the following method:

  • Declare the updated global variable and make it false ;
  • After entering the first table, I create an empty while until updated is true ;
  • Add a listener, as soon as the calculation is completed and the received event, set updated to true .

It seems unintuitive to me, but I can't think of another way to do it. Are there any good ways to do this?

Thanks for any inputs!

+7
source share
3 answers

Add a listener, as soon as the calculation is completed and the received event, set the update to true.

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

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

Running empty while loops is a bad idea. You not only record processor cycles, but Javacript is single-threaded, so you will forever go in cycles, giving anyone no chance to change the variable.

What you can do is rewrite the table in which there are other people, depending on it, to "trigger the event itself." There are many ways to do this, but basically you just want it to call the continue function instead of blind 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 } 
+5
source

You can write a callback function for any update triggers. To avoid messy callbacks, you can also use promises and update parts of the table depending on the data received in the update operation. Open for suggestions.

0
source

All Articles