javascript - how to print value regular interval of time? -
i using closure in java script print 1-10 value after each 2 sec.in other words first print 1 wait 2 second print 2 .i used closure nothing work .
here code.
for (var = 0; < 10; i++) { (function (index) { settimeout(function () { console.log(i); }, 2000); })(i); }
use setinterval
:
function loopwithdelay(callback, delay, max, min) { var = min || 0; if (i <= max) { var id = setinterval(function() { callback(i); if (++i > max) clearinterval(id); }, delay); } } loopwithdelay(function(i) { console.log(i) }, 2000, 10);
or use recursive settimeout
:
function loopwithdelay(callback, delay, max, min) { var = min || 0; if (i <= max) { settimeout(function() { callback(i); loopwithdelay(callback, delay, max, ++i); }, delay); } } loopwithdelay(function(i) { console.log(i) }, 2000, 10);
Comments
Post a Comment