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 many in a code setTimeout
, and each of these starts 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 el clearInterval
to each of them (imagining that there are more than 50 variables would be very tedious).
In general, any declared global variable is an attribute of the object
window
:But this doesn't work with local variables even when the context is
window
:My recommendation is to store the values directly in an array:
With the function
Object.keys(window)
you can get all the objects.Example:
I recommend that the var start with a more compound word (eg var aInterval = .... ), because if you use libraries or other things you could take other objects
I would do the following: create an array with the names of all possible variables, then iterate through it with
forEach
check if the objectwindow
has a "property" named as the variable in the array, if so, do whatever I need to do with it variable, if not, I show an error saying that said variable does not exist, example:You can store the identifiers of
setTimeout
andsetInterval
in an object as follows:Then, you can loop through the object:
I propose to use an object because variables are declared in your code, but you can also use a
Array
simple: