tags:

views:

93

answers:

2

I have a Javascript which is a little larger so I tried to show a .gif on the begin off the script and hide it after its finished. But if i do so the script runs and does all steps in one process so the picture is never shown. How can I force javascript to complete the show of the picture before run the rest of the script?

+3  A: 

Apart from the fact that it's not a good idea to have long-running javascript code, you could show the image and start the javascript using window.setInterval():

showBusy();
window.setTimeout(function() { startLongCode(); }, 100);

This will show the busy indicator and start your function 100ms later.

Philippe Leybaert
Just a 1ms delay should be enough to add async-ness (allowing the image to be shown in the document).
Ates Goral
+1, long-running javascript triggers warnings in some browsers to allow the user to stop the script. Some browsers have a max number of instructions, some have a grace period.If you bunch your instructions into a setInterval, processing 100-1000 items per iteration, you should be able to avoid it, and also have the ability to render progress bars or such like.
Lee Kowalkowski
A: 

You have to work with the Load event Jquery img.load question

-- EDIT

var myImg = new Image(); 
myImg.src = "my.jpg";

var myFunction = function(){
   //code...
}

myImg.onLoad = function() {
   myFunction();
}

Obj Img

You should extend this example to your need. I hope it will be useful.

andres descalzo
I don't think the OP is using jQuery (although it's a good suggestion)
Philippe Leybaert
not necessary to use jQuery. I edit the reply so you can see the example
andres descalzo