Search code examples
javascriptjquerycomputation

How to Append Text to DOM on click before expensive computational task


I have a function that performs a very expensive computational task on a click event. I'd like to append some text to the DOM right before this function gets called. Something like this:

$("#button2").click(function() {
    $('#progress').append('<p>Computing…</p>');
    run(); // Expensive computational task.  
    return false;
});

For some reason, the text doesn't get appended to the DOM until after the expensive computational task is finished. Why is this the case and how do I get around it?


Solution

  • The text does get appended right away - it's just that the browser doesn't refresh the screen until you are done executing javascript (it's waiting to see if you're making more changes to the DOM so it can reflow and repaint once for all changes).

    The way to get the screen to refresh right away is to return immediately and start run() on a very short setTimeout() like this:

    $("#button2").click(function() {
        $('#progress').append('<p>Computing…</p>');
        setTimeout(run, 1); // Expensive computational task.  
        return false;
    });