JavaScript recursive SetTimeout
A simple JavaScript solution for recursively setting timeout and running some operation periodically with maximum number of iterations support and only anonymous functions.
1 2 3 4 5 6 7 8 9 10 | (function(){ var t_count = 0; (function(delay, count) { setTimeout(function() { if (count && ++t_count > count) return; // do your stuff here setTimeout(arguments.callee, delay); }, delay); })(200, 10); })(); |
If you will omit second argument to anonymous function than operation will run infinitely.
1 2 3 4 5 6 7 8 | (function(){ var t_count = 0; (function(delay, count) { setTimeout(function() { //... }, delay); })(200); })(); |
Its even possible to constantly increase delay between operations.
1 2 3 4 5 6 7 8 | (function(){ var t_count = 0; (function(delay, count) { setTimeout(function() { //... }, delay * 0.5); })(200); })(); |