Question

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?

Was it helpful?

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;
});

OTHER TIPS

How about using setTimeout when calling run()

I'm not certain why that's the case, but why not defer the call to run until after you've appended the text? Try something like this:

$.when($('#progress').append('<p>Computing…</p>')).then(run);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top