¿cómo hacer una parada setInterval después de algún tiempo o después de una serie de acciones?


He creado un bucle de "cambiar palabras" con jQuery usando el código en esta respuesta: jQuery: Encuentra word y cambia cada pocos segundos

¿Cómo puedo detenerlo después de algún tiempo? digamos que después de 60 segundos o después de que haya pasado por el bucle?

Puedes ver las palabras cambiando aquí: http://skolresurser.se /

(function(){

            // List your words here:
            var words = [
                'Lärare',
                'Rektor',
                'Studievägledare',
                'Lärare',
                'Skolsyster',
                'Lärare',
                'Skolpsykolog',
                'Administratör'
                ], i = 0;

            setInterval(function(){
                $('#dennaText').fadeOut(function(){
                    $(this).html(words[i=(i+1)%words.length]).fadeIn();
                });
               // 2 seconds
            }, 2000);

        })();
Author: Community, 2012-02-04

4 answers

Para detenerlo después de ejecutar un número determinado de veces, simplemente agregue un contador al intervalo, luego cuando alcance ese número, límpielo.

Por ejemplo

var timesRun = 0;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 60){
        clearInterval(interval);
    }
    //do whatever here..
}, 2000); 

Si desea detenerlo después de que haya pasado un tiempo establecido (por ejemplo, 1 minuto), puede hacer:

var startTime = new Date().getTime();
var interval = setInterval(function(){
    if(new Date().getTime() - startTime > 60000){
        clearInterval(interval);
        return;
    }
    //do whatever here..
}, 2000);     
 81
Author: Mark Rhodes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-03 22:55:28

Use clearInterval para borrar el intervalo. Debe pasar el id de intervalo que obtiene del método setInterval.

Por ejemplo

var intervalId = setInterval(function(){
                    ....
                 }, 1000);

Para borrar el intervalo anterior use

clearInterval(intervalId);

Puede cambiar su código como se muestra a continuación.

(function(){

    // List your words here:
    var words = [
        'Lärare',
        'Rektor',
        'Studievägledare',
        'Lärare',
        'Skolsyster',
        'Lärare',
        'Skolpsykolog',
        'Administratör'
        ], i = 0;

    var intervalId = setInterval(function(){
        $('#dennaText').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn();
            if(i == words.length){//All the words are displayed clear interval
                 clearInterval(intervalId);
            }
        });
       // 2 seconds
    }, 2000);

})();
 4
Author: ShankarSangoli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-03 22:17:42

Deberías considerar usar un setTimeout() recursivo en lugar de setInterval() para evitar una condición de carrera.

var fadecount = 1;
(function interval(){  
    $('#dennaText').fadeOut(function(){
        $(this).html(words[i=(i+1)%words.length]).fadeIn('fast',function(){
            if (fadecount < 30){
                fadecount += 1;
                setTimeout(interval, 2000);
            }
        });
    });
}());
 2
Author: AlienWebguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-03 22:39:37

Puedes usar setTimeout en su lugar, lo cual es mejor:

(function foo(){ // wrap everything in a self-invoking function, not to expose "times"
  times = 20; // how many times to run
  (function run(){
    // do your stuff, like print the iteration
    document.body.innerHTML = times;

    if( --times ) // 200 * 20 = 4 seconds
      setTimeout(run, 100);
  })();
})();
 2
Author: vsync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-14 11:56:30