JavaScript equivalent of SwingUtilities.invokeLater()

3.3k views Asked by At

Is there any equivalent of Java's invokeLater() method of SwingUtilities in Javascript?

UPDATE 1

So, will setTimeout() with zero delay do exactly the same as invokeLater()?

2

There are 2 answers

2
Tomasz Nurkiewicz On BEST ANSWER
  1. If you want to run something asynchronously (later), try setTimeout()

  2. JavaScript is single-threaded. If you want to run some time consuming (CPU-intensive) task outside of the event handler, you can do this using the technique above, however it will still consume event-handling thread (cause your UI to freeze).

It is generally a bad idea to run CPU-intensive tasks inside a browser (web workers might change this) since they share the same thread as event handlers, making them wait.

See also

0
jpllosa On

Tried setTimeout, it made the UI give an impression that it was working but somehow it took a long time. Something like this:

for (...) {
    setTimeout(function() {
        // show a loading icon
        // AJAX call
        // heavy DOM manipulation
    });
}

Tried Promise. outcome was simply better and faster. So the code is now like this:

for (...) {
    var promise = new Promise(function() {
        // show a loading icon
        // AJAX call
        // heavy DOM manipulation
    });
}