Wilsonhut

Deal with it or don't

Tag Archives: asyncronous

Introducing… jQuery Gasp – Give a little breathing room to your browser-intensive jQuery

Have you ever done something like…

$("td").someBigNastyPlugin();

…and it was just too much processing for your browser? (I’m looking at you, IE)

It would be nice if your browser had a little bit of time to catch its breath while it’s trying to do all that processing.

jQuery.gasp to the rescue!

Include my gasp plug-in, and replace that code above with the following, and you’ll have a happy browser.

$("td").gasp(function(){
  $(this).someBigNastyPlugin();
});

Essentially, it’s like jquery’s .each function, but it puts a setTimeout around each one, and chains them together, one after the other. If you saw my defer plug-in, this will make more sense.

Now this is asyncronous, but it returns a promise, so you have to treat it accordingly:

$("td").gasp(function(){
  $(this).someBigNastyPlugin();
})
.done(function(){
  console.log("This will run when it's complete");
});
console.log("This will run before the gasping is finished");

The code for this plug-in is below, but the code below requires my jquery.defer plugin.

The jquery.gasp plug-in (on github) includes the jquery.defer code. Just seemed easier (for you) that way.

In later posts, I’ll show you some other cool things you can do with this other than give your browser a little relief. (Spoiler: Remember that $(…) can take things other than a selector string as an argument.)

;(function ($) {
    var defaults = {
		breathTime: 0,
		wait: 0
	};
	$.fn.gasp = function (func, options, promise) {
		options = $.extend({}, defaults, options);
		promise = promise || $.when();
		var isFirst = true;
		this.each(function () {
			var self = this;
			promise = promise.then(function () {
				var p = $.defer(function (el) {
					func.call(el);
				}, (isFirst? options.wait : options.breathTime), self);
				isFirst = false;
				return p;
			});
		});
		return promise;
	};
})(jQuery);
Advertisements