JavaScript – order of code execution

JavaScript is hardest to debug. Especially since you have to run it and put a whole bunch of alerts before you get to know what is wrong OR use Firebug! (but then your code should run the same in FF and IE). Today I had an issue where my JavaScript was running out of sequence.

Code:

1. Display 'Processing...' message
2. Perform lengthy operation

Cause: This can happen due to the some JavaScript code taking a longer time to run (like opening windows, calculations, modifying DOM) while the other part is more lightweight. eg.The user interface is updated after the the following JavaScript has finished. This is because the rendering engine and the script execution are queued on the same thread, and the GUI render waits for the script to finish.

Solution: use setTimeout()

var parameter1;
var parameter2;

function doSomethingCalledByProgram() {
// update GUI interface here
//update parameter1, parameter2 needed for
performBusinessLogic call
setTimeout( 'performBusinessLogic()', 100 )
}

function performBusinessLogic()
{
// Business logic here
}

Explanation: A separate thread is spawned, for the render engine, so that both operations can occur syncronously. Thus even if the large operation takes 10 seconds, the “Processing…” label will be shown as soon as the spawned thread finds a free cpu cycle, which will occur in 10-30 milliseconds whatever.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s