Search code examples
javascriptjqueryajaxcursorwait

How to change css property (like cursor:wait, or background) before AND after ajax calls?


I'm having problems with this code, I'm trying to show a red background while a function is working, and then (only then) I'm changing the background to green.

When the following alert is not commented, I can see the red background for a while and then the green (that's what I want).

But when I comment that alert, seems like the red background is never set and once processData has finished, the background is set to green, correctly.

Can somebody solve this mystery for me? thanks!

function beforeProcess(params){
    $('#result').css('background','red');
    alert('now i start waiting, while background is red');
    $.when(processData(params)).done(
        $('#result').css('background','green')
    );
}


function process(params){
     //This function takes some time, and it makes (indirectly) some synchronous ajax calls (async:false)
}

Solution

  • The view is only updated after the function finishes execution. This can be accomplished using a setTimeout http://jsfiddle.net/YEVHv/4/

    $('#result').css('background', 'red');
    //alert('now i start waiting, while background is red');
    setTimeout(function () {
        $.when(process("")).done(
        $('#result').css('background', 'green'));
    }, 0);
    
    
    function process(params) {
        for (var i = 0; i < 10000; i++) {
            console.log("hello");
        }
    }
    

    Hope that helps