javascript - How to save/clear setTimeout's array using loop's index? -


i calling loop multiple times. save single settimeout each index. idea use loop's index settimeout's array index, settimeout returns incremental id number, reset it, or override take control of returning id, can identify each timeout given index, within range of loop's index executed on , on again. being able use cleartimeout later on specific index.

var timeouts = []; for(var i=0; < 5 ; i++) {    ...    (function(delay, timeouts, i){       // keeps reference of timeout clear later.       timeouts[i] = settimeout(function() {          countinview--;       }, delay);       console.log("i: "+5+ " | timeout: "+timeouts[i]);       // i: 5 | timeout: 25 -> surpasses index,        // i'd override positions id or index.    }(delay, timeouts, i));    ... } 
  1. when loop executed more once, timeouts[i] value surpasses value of loop's index:

  2. i want clear timeout in other part of code, when reaching part of code, value of timeouts[i] may 140, , loop i value 3, never can clear 3rd(nor any) settimeout intended saved:

    cleartimeout(timeouts[i]); 

you use 2 dimensional array this, first dimension change along loop index, whilst second dimension remain in 0 take control of assigned timeout's ids each iteration.

for saving settimeout within index in loop

var timeouts = []; // 2  dimensional array (i = 0; < 5; i++)       timeouts[i] = [];  for(var i=0; < 5 ; i++) {     ...     (function(delay, $element, savedtimeout){         savedtimeout[0] = settimeout(function() {             countinview--;         }, delay, savedtimeout);     }(delay, $element, timeouts[i]));     ... } 

for clear settimeout within index in loop

if(timeouts[i][0] != null) {     //removes timeout queue     cleartimeout(timeouts[i][0]); } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -