Animated image does not move when javascript method is called for a long time

During a method that works for 10 seconds to add some elements to the html, the animated gif does not move at all, giving the feeling that the webpage is stuck. Anyway.

Code example:

    $ ('# button) .click (function () {   
        showAnimatedGif ();
        longRunningMethod ();    
        hideAnimatedGif ();
    });  

One way is to break the long running method into several steps and animate this path, but then you should write your code this way for each long method.

I wonder if there are other ways to do this?

+5
source share
2 answers

The only way to make sure that the animation is actually happening is longRunningMethodto periodically give way to the browser. It’s not uncommon for a UI display stream to block a JavaScript stream, so the changes you make to the DOM are not displayed until the next time a JavaScript stream appears. You can get it by calling setTimeoutwith a timeout 0(which will be more than 0ms - obviously - in most browser implementations; many clamp this value for at least 4 ms and, possibly, up to 10 ms).

Example: here is a script that adds a 500 div, but prevents the browser from showing the current work or (usually) animating something:

jQuery(function($) {

  $("#btnGo").click(function() {
    var n;

    display("Loading...");

    for (n = 0; n < 500; ++n) {
      $("<div/>").html("Div #" + n).appendTo(document.body);
    }

    display("Done loading");

    function display(msg) {
      $("<p/>").html(msg).appendTo(document.body);
    }
  });

});​

Real-time example * Spinner graphics example

, , , , , 500 .

, div:

jQuery(function($) {

  $("#btnGo").click(function() {
    display("Loading...");

    addDivs(0, 500, function() {
      display("Done loading");
    });

    function addDivs(current, max, callback) {
      if (current < max) {
        $("<div/>").html("Div #" + current).appendTo(document.body);
        setTimeout(function() {
          addDivs(current + 1, max, callback);
        }, 0);
      }
      else {
        callback();
      }
    }

    function display(msg) {
      $("<p/>").html(msg).appendTo(document.body);
    }
  });

});​

* spinner

, .

, script , , , . , , , . — , , , , .

+6

ajax. open.

xmlHttp.open('POST', ajaxurl, true);

.

0

All Articles