Monday, October 7, 2013

How to display a loading gif until a javascript function has been completed

The day may come when you come across the situation where you have so heavy javascript function that it actually takes some time to finish. While the code is running it freezes the UI which is not very user friendly but what can we do? Well, I'd say we have three options.

  1. The first thing I'd do is to check the logic of the code. If something is slow (speaking of javascript) there's probably better way to do it. But in some cases that's not an option. You may have actually written pretty decent code or you just don't have enough time to fix the whole past two years of someone's poor coding. Then I'd move to option two.
  2. Option two is Web Workers.

    "A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background." 

    Sounds ideal. And it is. But remember that Web Workers are not supported by IE 8 or other slightly older browser that are still in heavy use. So what do we do now?
  3. My third option would be to add a loading gif / loading text to the screen so that a user at least can tell there's something happening even if he's not be able to use the page while the script is running. And this is the topic of this post. 

How to show loading gif on the screen until the function has completed

So I created very simplified solution for this not-a-real-world example. See my solution in action. My code is below. I tried to comment the code so that you could have a sense what's happening there. But in a nutshell what I did.

A recursive function that waits one millisecond every time it's been called. You could think this as a home-made FOR-loop since we're keeping track of the quantity of function calls. Anyways, you could have this without a counter so that It would run till the end of the world. It would not freeze the browser because the timeout.



I hope this will help you in a way or another.

No comments:

Post a Comment