<script> function foo(c) { var a = 2, b = !1; return function() { b ? a++ : a--; if (a == c || 1 == a) b = !b; return a } }; var x = foo(5) for (var i=0; i<50; i++) {document.write(x()+ ' ')} </script>