My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Wednesday, December 03, 2008

Stressfull procedure? Distribute your task!

Have you never been in troubles with frozen GIFs or unresponsive HTML?
Sometimes JavaScript could be used to perform really stressful task and a loop, a for in, or an each, could not be fast enough to make your DOM responsive.

What we need in this case is simply a closure to make sure references are consistent and our job will end up in the correct order.

This is a probably silly but I hope interesting function to make the DOM and generally the page more responsive:

Time = {
setTimeout:function(Stack, delay){
var self = this;
if(!delay)
delay = 1;
if(!(Stack instanceof Array))
Stack = [Stack];
setTimeout(function(){
Stack.shift().call(self);
if(0 < Stack.length)
setTimeout(arguments.callee, delay);
}, delay);
}
};

We can call this functon in different ways, stating from the demo:

Time.setTimeout([
function(){
alert("Hello");
},
function(){
alert("Distributed");
},
function(){
alert("Work");
}
]);

untill its more meaningful usage:

var distributed = [];
$("whatever").each(function(i, dom){
distributed.push(function(){
// your stuff to do with i or dom element
});
});
distributed.push(function(){
// your stuff to do after the each call
});
Time.setTimeout(distributed);

Another trick? The usage of the scope injected by each function:

$("whatever").each(function(i, dom){
var self = this;
distributed.push(function(){
return function(){
// your stuff to do with i or dom element
}.call(self);
});
});

Closures against Responsiveness


People expect usability, we expect performances ... at the same time we would like to be able to show a progress, something, that indicate that the page is not completely blocked.

This is a simple way to solve the problem, portable enough, and customizable via closures ... I hope you'll enjoy it :)

2 comments:

Anonymous said...

Very interesting... I'm looking into some scripts that make the page unresponsive the more nodes it has... I thought about html5 threads("workers") but sadly they can't manipulate DOM... so I guess this is the way to go... thank you.

Beben said...

I've read your post, although do not understand it but interesting to read ... from Sept 2006 to Dec 2008
hihihi :D cheers...