Simulating DoEvents in JavaScript

Anyone who comes from a Windows programming background will have some familiarity with the good old Application.DoEvents(); command in .NET, and maybe even the plain and simple DoEvents() from prehistoric VB6 days. DoEvents() basically hands control back to Windows to do whatever it needs to do to keep things ticking along smoothly before continuing with your code. It is a cheap and dirty way to stop your application from hanging:

while (something interesting happens) {
	Do[The.Really.Tricky.Stuff].Here();
	Application.DoEvents();
}

Unless you’ve put it in a different thread, without Application.DoEvents(); in the block above your app would simply hang until it had finished doing its work.

I was recently doing some JavaScript code and had a requirement to keep a loop of JavaScript running constantly in the background, checking stuff interactively while the page was open. Starting with something like this just doesn’t work:

while (true) {
	DoMyChecks(Here);
}

The whole browser session freezes. Instead you need to structure your code slightly different, and take advantage of the setTimeout() function:

function myConstantProcess() {
	DoMyChecks(Here);
	setTimeout("myConstantProcess()",100);
}

You can then call that function once using myConstantProcess(); and it will run constantly while the browser window is open. You can vary the frequency with which your function runs by changing the second parameter of setTimeout() (100 in the example above) – this is the time to wait in milliseconds before launching the function again.

1 Comment

[...] function is a self-repeating function that actually manages the movement in a smooth way. It calls itself every 20 miliseconds while there is work to do, and increments the toolbar by 1px either upwards or downwards, depending [...]

Leave a comment

Your comment