is there a way to show a loading image while a JavaScript function is running. I have one that takes about 2-5 seconds, would be nice if i could have something like the jQuery-ajax function
$("#loading").bind("ajaxStart", function(){
$(this).attr("style", "visibility: visible")
}).bind("ajaxStop", function(){
$(this).attr("style", "visibility: hidden")
});
clarification edit:
The idea is that every time a JavaScript function runs and takes over, say 3/4 of a second, the loading image would be displayed. It really has nothing to do with this ajax function, just the same principle of always catching a running JavaScript and timing it.
Thanks!
Well then… After you commented, that changes everything.
You cannot have it automatically show when any javascript runs because there is no real hook for that. You can however leverage jquery custom events through the use of
.trigger()and.bind()using your own custom event.Although long running operations should probably be done asynchronously so they don’t block on the event:
Then register a
.bind()event much like.ajaxStart()and.ajaxStop()Here is a working jsFiddle Example.
Update:
In your jsFiddle you’ve done a double
setTimeout. Here:What this translates to is:
So the
Custom.Endevent is getting fired after scheduling the long running function to run, not when it completes.setTimeoutis asynchronous and non-blocking.