I am having trouble using the clearInterval function

3
a_103 = setInterval( function (){ alert('oi');},3000);
id = 103;
id = "a_" + id;
clearInterval(id)

I'm having problem with clearinterval . It can not perform the way I did, but if I by clearInterval (a_103); It usually goes.

I have changed: clearInterval (eval (id))

    
asked by anonymous 11.03.2014 / 19:38

2 answers

2

Another option is to not try to create variables with dynamic names, but use a map type for this.

Example:

var intervalos = [];
intervalos['a_103'] = setInterval(function(){ console.log('oi'); }, 3000);
...
clearInterval(intervalos['a_103']);

A more complete example of creating and cleaning timers :

var intervalos = [];

//cria intervalos de a_1 até a_150
for (var i = 0; i < 150; i++) {
    intervalos['a_' + (i+1)] = setInterval(
        function(){ console.log('oi'); }, 
        3000 + i * 100);
}

//depois
for (var i = 0; i < 150; i++) {
    clearInterval(intervalos['a_' + (i+1)]);
}

//ou
clearInterval(intervalos['a_103']);

Jsfiddle

    
11.03.2014 / 20:03
1

You can use the eval() function:

a_103 = setInterval( function (){ alert('oi');},3000);
id = 103;
id = "a_" + id;
clearInterval(eval(id))

Example: FIDDLE

    
11.03.2014 / 19:49