Friday, April 10, 2009

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.

No comments:

Post a Comment

Thank you for your feedback