javascript – Find variables in a document

Question:

var a1 = setTimeout(function(){});
var a2 = setTimeout(function(){});
var a3 = setTimeout(function(){});
var a4 = setTimeout(function(){});
var a5 = setTimeout(function(){});

if(){
clearInterval(a1);
clearInterval(a2);
// etc..
}

If I had in a code many setTimeout , and each of these begins with a variable called "a" + un número , how could I identify all the variables that start with a and then with a number, in order to put them in an array and go through them to apply the clearInterval , instead of doing the clearInterval to each one of them (imagining that there are more than 50 variables would be very tedious).

Answer:

In general, any declared global variable is an attribute of the window object:

var a1 = 5;
var a2 = 6;
var a3 = 'hola';

let i = 1;

while(window['a' + i]) {
  console.log('La variable a' + i + ' vale ' + window['a' + i]);
  i++;
}

But this doesn't work with local variables even when the context is window :

(function () {
  var a1 = 5
  var a2 = 6
  var a3 = 'hola'

  let i = 1;

  while(window['a' + i]) {
    console.log('La variable a' + i + ' vale ' + window['a' + i]);
    i++;
  }
  
  console.log('El contexto es: ', this.toString());
})()

My recommendation is to save the values ​​directly in an array:

let timeouts = [];

for (let i = 0;i < 5; i++) {
  timeouts.push(setTimeout(() => console.log('Hola ' + i), i * 2000));
  // Al usar let en lugar de var, cada callback tiene un valor distinto para i ;)
}

setTimeout(() => {
  timeouts.forEach(id => clearTimeout(id));
//clearTimeout en el caso presente, no clearInterval
  console.log('Eliminados los timeouts no ejecutados');
}, 3000)
Scroll to Top