Loading Spinner with jQuery Promises

In your website you want to call a web service that performs some long running task. It may be loading a large set of data or performing a complex calculation on the server, so you want to animate a spinner or a loading indicator over the screen or component.

You can achieve this effect using jQuery promises.

Assume your web service call looks like this :

Because your function returns an AJAX object it can be used with the $.when function in jQuery.

If you start your spinner, then place your function in the $.when function, and then disabling the spinner in the always block, you will get seamless spinner activity.

All I am using for the spinner is an extjs loading panel using the call window.setLoading(true). However most frameworks have some kind of a spinner, or progress bar. Eg. angular has http://fgnass.github.io/spin.js/ .

Promises tidy things up by not needing to have the callback method inside the ‘always’ block in the ajax code, making the method more reusable.

Posted in JavaScript | Tagged , , | Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">