How to set the number of times setInterval will run?

6

Is it possible to control the number of runs of setInterval ? I made a very simple script where I wanted to div blink 3x to alert the user. But in the script I did it it blinks straight.

<div id="my-div">alerta teste</div>

setInterval(function(){
      $('#my-div').animate({'opacity':'toggle'})
},250);
    
asked by anonymous 23.11.2015 / 19:35

3 answers

12

You can create a flag that checks how many times this code has been run.

Something like this:

var qtd = 0;
var pisca = setInterval(function () {
    $('#my-div').animate({
        'opacity': 'toggle'
    })
    qtd++;
    if (qtd > 3) clearInterval(pisca);
}, 250);

So every time the setInterval is run the variable qtd adds 1 . Within the setInterval condition if checks the value and "turns off" the setInterval when the condition gives true .

An example would be: link


Alternative with callback :

var qtd = 6;

function pisca() {
    if (qtd--) $('#my-div').animate({
        'opacity': 'toggle'
    }, pisca);
}
pisca();

See the JS Fiddle

    
23.11.2015 / 19:39
5

The @Sergio response responds exactly to what was asked, but it is a supplementary suggestion to setTimeout , which may be more interesting than setInterval in its specific case, and simplifies the syntax:

var qtd = 5;
function pisca(){
    $( '#my-div').animate({ 'opacity': 'toggle' } )
    if (qtd--) setTimeout( pisca, 250 );
}
setTimeout( pisca, 250 );
Demonstração:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><divid="my-div">TESTE</div>
    
23.11.2015 / 20:06
1

In function form:

function setIntervalLimit(func, time, limit){
    var n = 0; // CRIA UM CONTADOR INTERNO
    var f = function(){ // CRIA UM FUNCAO INTERNA
        func();
        n++;
        if(n < limit){ // VEFIFICA CONTAGEM
            setTimeout(f, time); // REALIZA LOOP
        }
    }
    f(); // CHAMA A FUNÇÃO INTERNA 1ª VEZ
}

setIntervalLimit(function(){
    alert('a');
}, 1000, 3);

The operation is similar to SetTimeout , however with a third parameter to tell the number of executions.

Obs

limit should be > 0, otherwise it generates loopinfito.

    
24.11.2015 / 17:25