Find variables in a document

10

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 you had a many setTimeout , and each of these starts with a variable called "a" + un número , as you could identify all the variables that begin with ay then with a number, to put them into an array and go through them to apply the clearInterval , instead of doing the clearInterval to each of them (imagining that there are more than 50 variables would be very tedious).

    
asked by Eduardo Sebastian 05.09.2017 в 18:10
source

4 answers

5

With the Object.keys(window) function you can get all the objects.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
	<script>
		var a1 =  setInterval(function(){console.log("txt1");},1000);
		var a2 =  setInterval(function(){console.log("txt2");},1000);
		var a3 =  setInterval(function(){console.log("txt3");},1000);
		var a4 =  setInterval(function(){console.log("txt4");},1000);
		var a5 =  setInterval(function(){console.log("txt5");},1000);

		function detenerObjetosInterval(){
            //obteniendo objetos
			var objetosTodos=Object.keys(window);
			var objetosInterval=[];
			//obteniendo objetos que inicia con 'a'
			for(i = 0 ; i < objetosTodos.length ; i++){
				if(objetosTodos[i].indexOf('a')==0){
					objetosInterval.push(objetosTodos[i]);
				}
			}
			//deteniendo objetos
			for(i = 0 ; i < objetosInterval.length ; i++){
				clearInterval(eval(objetosInterval[i]));
			}
		}
		
		//detener intervals despues de 5 seg
		setTimeout(function(){
			console.log("deteniendo intervals");
			detenerObjetosInterval();
		},5000);
	</script>
</head>
<body>
</body>
</html>

I recommend that the var start with a more compound word (ahem var aInterval = .... ), because if you use libraries or other things you could pick up other objects

    
answered by 05.09.2017 / 20:20
source
11

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

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

var i = 1;

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

But this does not work with local variables even when the context is window :

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

  var i = 1;

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

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

var 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)
    
answered by 06.09.2017 в 12:51
1

I would do the following: I would create an array with the names of all the possible variables, then I would run it with forEach I would check if the object window has a "property" called as the variable in the arrangement, if so, I do what I have to do with that variable, if not, I show an error saying that said variable does not exist, example:

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

const possibleVariablesNum = 10;
var possibleVariablesArr = [];

for(var i = 0; i <= possibleVariablesNum; i++){
  possibleVariablesArr.push("a" + i.toString());
}

possibleVariablesArr.forEach((value, index) => {
  if (window.hasOwnProperty(value)) {
    console.log("La variable " + value + " existe y se limpiará");
    clearInterval(window[value]);
  }else{
    console.error("La variable " + value + " NO existe");
  }
})
    
answered by 05.09.2017 в 18:17
1

You can save the identifiers of setTimeout and setInterval in an object as follows:

let itervals = {
    a1: setInterval(()=>{}, 100),
    a2: setInterval(()=>{}, 100),
    a3: setInterval(()=>{}, 100)
}

Then, you can go through the object:

for(let i in intervals){
    clearInterval(intervals[i]);
}

I propose to use an object because the declared variables are in your code, but you can also use a simple Array :

let intervals = [
    setInterval(()=>{}, 100),
    setInterval(()=>{}, 100),
    setInterval(()=>{}, 100),
]

for(let i in intervals){
    clearInterval(intervals[i]);
}
    
answered by 06.09.2017 в 12:04