Force immediate DOM update modified with jQuery in long-running function
Asked Answered
O

1

10

I have a javascript that takes about 2 seconds to execute (complex optimization algorithm). I want to set certain span to "working..." at the beginning of the function. I observe that the span doesn't change until the end of the function.

How can I force DOM changes propagation? or should I approach this differently all together?

I call the function from onclick on the button.

The function is something like:

function optimize() {
    $('#status').text('working...');
    // calculate for 2 seconds
    $('#status').text('done!');
}
Ogdan answered 23/10, 2010 at 17:1 Comment(1)
That should work. Could you give a link to the non-functioning code?Uriel
W
12

Try wrapping the long running code in a setTimeout call:

function optimize() {
    $('#status').text('working...');
    window.setTimeout(function() {
        // calculate for 2 seconds
        $('#status').text('done!');
    }, 0);
}

This forces a new call stack for the long running code, allowing the repaint (changing of the text) to complete before the new call stack begins execution.

Wingfield answered 23/10, 2010 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.