A slightly better approach to using the immediately called function in each iteration is for the log() function to return the function.
(function(){ function log(s){ return function() { if(console && console.log) console.log(s); else alert(s); }; } var i = 10; while (i--){ window.setTimeout( log( i ),500 ); } })();
The overall result is that you create fewer function objects.
If you want calls to be made at intervals, use setInterval() or change this:
window.setTimeout( log( i ), 500 );
:
window.setTimeout( log( i ), i * 500 );
source share