javascript - Trouble with multiple age counters (timers) -


i have page want have "age counters" bids put in users. number of users vary situation situation, needs taken consideration. wrote this:

function timer(i) {           // selects 'hh:mm:ss' timestamp         if ($("#time_0" + i).text() !== "") {             var = new date();             var date = now.todatestring();             var tstamp = new date(date + "," + $("#time_0" + i).text());             var diff = - tstamp;             var mins = math.floor(diff / (1000 * 60));             var secs = math.floor((diff / 1000) % 60);             if (mins < 10) {                 mins = "0" + mins;             }             if (secs < 10) {                 secs = "0" + secs;             } else if (secs == 60) {                 secs = "00";             }             $("#user" + + "-t").text(mins + ':' + secs);         } }  $(document).ready(function() {                     //             var ids = [];             $("td[id^='time_0']").each(function() {                 var = ($(this).attr("id")).slice(-1);                 ids.push(i);             });             (i in ids) {  // in example ids = [1,2,3]                 setinterval(function() {timer(i);}, 1000);             } }); 

the timer functions want to, user #2 (the middle one). thought if encountered problem, either first or last user in list had working timer, i'm getting blank cells users #1 , #3.

does have ideas how can fix this? thank time.

==edit==

i made bare-bones jsfiddle

in version loop never went past first reference, timer(0), because called function timer(i), calling first key in array ids. when have setinterval in loop keep looping first setinterval until terminated. putting i in anonymous function, each setinterval gets fired.

$(document).ready(function () {     var ids = [];     $("td[id^='time_0']").each(function () {         var = $(this).attr("id").slice(-1);         ids.push(i);     });      (i in ids) {         (function(i) { // needs stored anonymous function otherwise gets overwritten             setinterval(function() {                 timer(ids[i]); // calling timer(i) use array keys, not actual values - ids[i] means: "give me value of key of i"             }, 1000)         })(i);     } }); 

made changes fiddle


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -