Question

I want to display a spinner before some complicated function, i.e. dummyCounter(). The code looks like:

function add1() {
  msg.html('start counting~<br \>');
  document.body.appendChild(div);  
  spinner.spin(div);  
  // display spinner before doing stuff

  dummyCounter();  
}

jsfiddle: http://jsfiddle.net/eGB5t/

However the spinner shows after the dummyCounter() function is finished.

I try to use callback to force spinner display earlier but still no good. Can anybody help? Thanks.

jsfiddle: http://jsfiddle.net/eGB5t/2/

Était-ce utile?

La solution

You have a thinking failure. Spinners are usually used for asynchronous tasks, so you can see that there is something in progress. A callback is then used to remove the spin when the async action has finished, since you cannot tell before it starts when it will finish.

I made up a quick example to show you, how such an async function would work in this case, and you can clearly see how the spinner appears slightly before "google finished" appears. http://jsfiddle.net/eGB5t/4/

I added the following instead of your counting method:

$.ajax("http://google.de").always(function() {
    msg.append("google finished");
});

You add the spin before you count, then it counts, then you could remove the spinner. This is perfecty fine. Thing is, if you would count to let's say 9999999999999 (so it would take some seconds), a normal for loop like you're doing is completely blocking the browser, so you won't have any repaints (and therefore no spinner) at all, while the loop is running.

What you would have to do (in this case) is to introduce a worker to have multithreading functionality in javascript.

Autres conseils

var x;
function add1() {
  msg.html('start counting~<br \>');

spinner.spin(div);
x= setTimeout(document.body.appendChild(div),500);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top