var counter = 1; function foo() { if (counter < 5){ counter++ window.setTimeout(foo, 1000); } } foo()
Live demo
Version with static variable:
function foo() { if (typeof foo.counter == 'undefined') { foo.counter = 0; } alert("Run No. " + (++foo.counter)); if (foo.counter < 5) { setTimeout(function() { foo(foo.counter + 1); }, 400); } } foo();
Live demo
Version with hidden input
function foo() { var counter = document.getElementById('counter'); var counterValue = parseInt(counter.value, 10); alert('Run No. ' + counterValue); if (counterValue< 5) { counter.value = counterValue + 1; window.setTimeout(foo, 400); } } foo();
Live demo
Closed Version:
var x = function() { var counter = 1; (function foo() { alert('Run No. ' + counter); if (counter < 5) { counter++; setTimeout(foo, 400); } })(); }; x();
Live demo
gdoron
source share