Domanda

I want my javascript/jquery application to stop executing all animations, and only continue executing when a loading .gif is shown.

I did manage to show the loading .gif while other animations where going on, but I really need it to already show before anything else is animated.

So I fabricated a method that waits for the callback to be executed, but it doesn't work as expected.

var Shown = false;
function ShowLoadingGif() {
    $("#loading").show("fast", function() {
        Shown = true;   
    });
    while(!Shown) {
        //wait for callback to be executed
    }
    Shown = false;
}

See this JFiddle example. I would not only like to know how to properly go about solving this problem; I would also appreciate any input as to why it doesn't work as I expect it to.

Thanks in advance!

È stato utile?

Soluzione

You can use something like this, using the jQuery Deferred Object ( see Docs )

var Shown = false;
function ShowLoadingGif() {
    var $promise = $.Deferred();
    $("#loading").show("fast", function() {
        $promise.resolve("Im done");
    });
    $promise.done(function(data) {
         // data === "Im done"
    });
}

I have updated your Fiddle that now alerts when the stuff has finished as you would expect

Fiddle (http://jsfiddle.net/k5Wan/3/)

Also I have updated the code quality

var $promise = $.Deferred();

$promise.done(function() {
    alert("Done...");
});

$(function() {
    $("button").on("click", function() {
        $("#loading").show("slow", function() {
            $promise.resolve();
        });
    });
});

Altri suggerimenti

You can shorten all that:

$('#loading').show('fast', function(){
  console.log('Im loaded');
}).promise().done(function(){
  console.log('great loading with you!');
});

DEMO

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top