I’m having trouble using the clearInterval function

Asked

Viewed 210 times

3

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

I’m having trouble in the clearinterval. Can not do the way I did, but if I clearInterval(a_103); It will normally.

changed: clearInterval(Eval(id))

  • could have used clearInterval(window[id]) if the scope is comprehensive

2 answers

2

Another option is not to try to create variables with dynamic names, but to 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, creating and cleaning several 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

  • Thank you, already manage to solve.

  • 2

    Although my answer is simpler, I consider yours to be correct, as well as avoiding the use of eval() (that many do not recommend) still allows an undetermined number of intervals without the need to create other "dynamic variables".

  • @Kazzkiq Yes, your answer goes straight to the point. I just wanted to indicate a possibly more "clean" alternative, in the sense of not using Eval.

1

You can use the function eval():

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

Example: FIDDLE

  • Thanks, I managed to solve my poblema.

  • @Dieguinhorodrigues just a hint, if any of our answers solved your problem, ideally you mark it as correct so that users who have the same problem as yours can know which solution best served you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.