Javascript DOM blocking

Leave a Reply

Comment as a guest.

    1. I’m inclined to believe that the wait time you’re describing is the interpreter/JIT compiler running through the rest of the function before running the actual setTimeout() call, rather than it delaying the setTimeout() randomly.

      1. It’s not random: http://www.w3.org/TR/html5/timers.html#timers
        For setTimeout():
        “If the currently running task is a task that was created by the setTimeout() method, and timeout is less than 4, then increase timeout to 4.”
        and for setInterval():
        “If timeout is less than 10, then increase timeout to 10.”

        1. Great find! This explains why setTimeout(func, 0) seems to work. I guess the next experiment would be to see whether something that would take >4 ms (or even, say 100 ms) would still be blocked by the setTimeout(); I’d guess no.

    1. Well, this is more of a toy problem, and I’ve run across other times where there’s less of a workaround (e.g., adding a style directly, hooking up an event handler).

  1. Also, you might consider chaining the code:
    $input.addClass(‘show’).focus();
    Ideally, focus will only be called once it gets the object(s) returned by addClass — automatically removing any async behaviour.

    1. I don’t think chaining helps; like you say, the problem is that I have to make the focus call happen after addClass has fully executed, and in JS that’s communicated via a callback.

  2. I’m not certain about this.. Just taking a stab in the dark, but would jQuery’s (assuming that’s what your $ is an instance of) show() help here?
    Ie. $input.show().focus()?
    Maybe jQ does some reflow-waiting magic in that function..

Sliding Sidebar