3

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()?

Dims
  • 47,675
  • 117
  • 331
  • 600
  • 1
    I think you missed the point of @Tomasz's answer: `setTimeout()` will never do the same as `invokeLater()` because it will *block your UI thread* while invoking the delayed function. – Frédéric Hamidi Jan 20 '12 at 20:08
  • I think the question is whether it will always return immediately and execute its function argument directly from the UI loop, even with an argument of zero, or instead sometimes execute the function immediately. – yeoman Apr 15 '17 at 12:55
  • 2
    @FrédéricHamidi so does Swing's invokeLater. That also always runs its argument on the UI thread but it guarantees to always return immediately and perform the execution directly from the event loop. – yeoman Apr 15 '17 at 12:56

2 Answers2

4
  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

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
0

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
    });
}
jpllosa
  • 2,066
  • 1
  • 28
  • 30