Tuesday, September 9, 2008

Creating time delays in Javascript

Creating time delays
There are two ways of creating time delays with JavaScript. The first is more simple and will simply wait for a specified amount of time before executing a function. The second does the same but will repeatedly execute the function.

Note, most browsers have a minimum delay length of between 25 and 75 ms. If a shorter delay is specified, the actual delay will be the minimum delay length. Even with higher numbers, the delay is never perfect. Most browsers will take slightly longer than the time you ask for, typically just a few miliseconds error. Some may correct their errors over time with interval timers. Also note, setting many timers with short delays on one page will cause the browser to become slow and somewhat unresponsive. Three or four timers is usually the reliable limit.

setTimeout
The first method uses a window method called setTimeout(). The method waits for a specified number of milliseconds then executes the specified code. The code can either be a direct reference to a function, or it can be a string that will be evaluated as if it contained source code.

window.setTimeout(referenceToFunction,timeInMilliseconds);window.setTimeout('runMoreCode()',timeInMilliseconds);Wherever possible, you should use a direct function reference as it is much more efficient. Using a string requires the browser to create a new script environment so it can process the script.

If you create a timeout, the code after the call to setTimeout will continue to run as normal. After the specified delay, the timeout will start a new thread, and the code specified in the call to setTimeout will be run in the new thread, along side any code that is still running in the initial thread. Unlike with many more complex languages, JavaScript does not offer any way to control when those threads sleep, wake, or yield. The JavaScript engine handles all of that, and you must accept that your new thread could be executing at any time next to another thread. Many JavaScript engines will simply allow one thread to complete before allowing the other thread to start. The same applies to events, which run in their own threads, and can be triggered at any time.

More...
http://www.howtocreate.co.uk/tutorials/javascript/timers

ASP.Net Feeds