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

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -