javascript - Why does my iterator variable keep resetting? -


i have array populated numbers. want display new number every 5 seconds in alert() popup. have appears working part, resets before showing number 3. @ first shows 1, shows 2, shows 1 again. can't figure out. maintain syntax part if can. don't understand why counter keeps resetting 0.

var arr = [1, 2, 3, 4, 5]; var maxloops = number(arr.length); var counter = -1;  (function next() {     if (counter++ > maxloops);     settimeout(function() {         alert(arr[counter]);         next();     }, 5000); })(); 

the issue here value of counter may change between setting timer , calling anonymous function within it. alleviate problem, value of counter must passed timer function.

var arr = [1, 2, 3, 4, 5]; var maxloops = number(arr.length) - 1; var counter = -1;  (function next() {     if (counter++ >= maxloops) return;     settimeout((function (c) {         return (function() {             alert(arr[c]);             next();         });     })(counter), 5000); })(); 

personally, write follows:

var arr = [1, 2, 3, 4, 5];  (function next(counter) {     if (counter < arr.length) {         settimeout(function () {             alert(arr[counter]);             next(counter + 1);         }, 5000);     } })(0); 

this implementation ensures next has local copy of counter, value not change while function runs, timeout function uses correct counter value each time.

if page getting refreshed (for whatever reason), set timeout functions following "one-liner":

var arr = [1, 2, 3, 4, 5];  arr.foreach(function (e, i) {     settimeout(function () { alert(e); }, 5000 * (i + 1)); }); 

Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -