Writing Responsive Code in Javascript

So, in the beginning all the things you’ve done in Javascript runs quick as the rabbit and your application feels very snappy. But after a while as your code is getting more complex and growing in size, you’ll probably experience that the application is not as responsive as you wish. Here’s a technique to help you out, which was a bit of an eye opener for me.

Consider the following example:

Click me, please!
function myFunction() {
	updateStatusMessage('Working..');
	someCpuIntensiveCode();
	updateStatusMessage('Done!');
}

$('mylink').observe('click', myFunction);

The function updateStatusMessage() is suppose to update an element on the page as soon as the user clicks on the link, which will indicate that something is happening. But since your javascript code compete with the UI-thread, the browser probably doesn’t do the update until the function has finished. The solution is to delay the code that prevents the browser to update using the function setTimeout() and give the browser a chance to refresh the UI before the cpu intensive code executes.

Here’s the trick:

function myFunction() {
	updateStatusMessage('Working..');
	setTimeout(function() {
		someCpuIntensiveCode();
		updateStatusMessage('Done!');
	}, 10);
}

You may have to tweak the timeout in order to see any effect.

Now wrap it up so we can reuse the code for other operations too:

function heavyFunction(func, timeout) {
	timeout = timeout || 10;
	updateStatusMessage('Working..');
	setTimeout(function() {
		func();
		updateStatusMessage('Done!');
	}, timeout);
}

function myFunction() {
	heavyFunction(someCpuIntensiveCode);
}

function myOtherFunction() {
	heavyFunction(function() {
		moreCPUIntensiveCode(arg1, arg2);
	});
}

Click here for a working example!

For more information about this topic, take a look at the excellent screencast High-performance JavaScript: Why Everything You’ve Been Taught Is Wrong which gave me some light in the dark.