خرید بک لینک

Vote count: 0

I have a for loop, and I would like to save a setTimeout for each iteration, using the loop's index as setTimeout's array index, so that I am able to use clearTimeout later on with an specific index.

for(var i=0; i < 5 ; i++) {
   ...
   (function(delay, timeouts, i){
      // Keeps a reference of the timeout to clear it later.
      timeouts[i] = setTimeout(function() {
         countInView--;
      }, delay);
   }(delay, timeouts, i));
   ...
}

  1. I don't understand why, when logging the value of timeouts[i] after assign, its value correspond with an integer number, instead of an object reference of the setTimeout.

    ...
    (function(delay, timeouts, i){
        timeouts[i] = setTimeout(function() {
           countInView--;
        }, delay);
        console.log("value is: "+timeouts[i]); // value is: 5  -> Is an integer,
                                               // not an object reference
    }(delay, timeouts, i));
    ...
    
    
  2. When the loop is executed more than once, the timeouts[i] value surpasses the value of loop's index:

    // 5th time executing this loop
    for(i = 0 ; i < 5 ; i++) {
        ...
        (function(delay, timeouts, i){
            timeouts[i] = setTimeout(function() {
                countInView--;
            }, delay);
            console.log("i: "+5+ " | timeout: "+timeouts[i]);
            // i: 5 | timeout: 25 -> Surpasses index, 
            // as if it couldn't overwrite positions.
        }(delay, timeouts, i));
        ...
    }
    
    
  3. I just want to clear the timeout in other part of the code, but when reaching this part of the code, the value of timeouts[i] may be 140, and loop i value only 3, so I never can clear the 3rd setTimeout intended to be saved:

    clearTimeout(timeouts[i]);
    
    
asked 2 mins ago

برچسب: نویسنده: استخدام کار تاريخ: شنبه 8 خرداد 1395 ساعت: 17:42

صفحه بندی