Tuesday, February 28, 2012

Javascript setTimeout and setInterval or How I learned to love to sleep in javascript


kick it on DotNetKicks.com
This is a bit of a self reminder for dealing with "sleep" or "wait" related actions in javascript. Reason for it was because I had an whiteboard interview question that required me to use some type of "sleep" or "Wait" functionality in javascript and I almost never actually needed to use either.

These functions are baked in javascript tools
setInterval (fn,num);
setTimeout(fn,num);

About setInterval

Calls passed function(fn) repeatedly at the interval given in milliseconds.(num)

Note* Calls passed function(fn) after a bare minimum number of milliseconds. Although
it can be longer depends on the number of events waiting on the async queue of the browser.

About setTimeout

Returns the id of the thread fired to be used as a reference for clear Interval(id)

How setInterval and setTimeout are the same

  • Both function take two parameters
  • the first being a function and the second being an int
How setInterval and setTimeout are different

The number is the minimum number of milliseconds to wait before the passed function is run in the case of setTimeout but, with setInterval the function will run repeatedly with no regard for the previous run. In other words setInterval is non blocking and each call back exists independently of page state.
See how-javascript-timers-work for deeper insight with John Resig.