jQuery, Each() and Async Gets

You can also get the feed via email. Sign up now by supplying your email address and clicking the Subscribe button

One of the things to keep in mind when using jQuery is that nothing is a blocking call. Sure, there is a certain sequence to when things operate. But, to be safe, you should always assume that step two will happen during step one.

Nowhere is this more evident than when retrieving content from a URL and inserting that content in your page.

The problem with this is that jQuery.get is an asynchronous call. This means that once the get has fired, the each loop will continue. This can cause all kinds of trouble for you, including having a complete iteration skipped, or if you are doing some kind of concatenation prior to inserting the HTML, having HTML for one iteration showing up in the middle of another.

Not exactly what you had in mind, eh?

But there is a fix. Use the ajax call instead and specify async:false to force the call to complete before allowing another call.

Like this Article? Subscribe to get every article sent to your email.

Related Post

jQuery – Accordion If you’ve been using the MS-AJAX Accordion control, stop it right now!Seriously. Once I show you how easy the jQuery version is, you’ll want to drop it. Shoot! You may even want to […]

jQuery – Calling Your Own Functions While jQuery has a lot of functionality built into it, you may find that you have a need to implement your own functions and attach them to the jQuery framework in some way.There are […]

JQuery, Cufon, and Dynamic Content Yesterday I mentioned a new tool called Cufon that allows you to easily embed fonts in your web site. One quirk about this tool is that your HTML has to be rendered prior to applying, […]

jQuery and ASP.NET UpdatePanel I’ve been busy over the last couple of weeks working on an administrative application that uses a ton of AJAXy stuff. The application is interactive in the sense that every time a field […]

C# Properties Get and SetMy son is learning to program. Last week he asked me to explain C# properties get and set and, as it turns out, it looks like many others are asking for the same. So, I’ve decided […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer. His commitment to quality through test driven development, vast knowledge of C#, HTML, CSS and JavaScript as well as his ability to mentor younger programmers and his passion for Agile/Scrum as defined by the Agile Manifesto and the Scrum Alliance will certainly be an asset to your organization.

I’m not sure what your point is. I never said anything about $.each being async or not (it isn’t btw). My point was that the get is async and you can use the ajax call instead to FORCE synchronous if that is what you need (which often you do not.)