setInterval how to come back again after giving a clearInterval?

0

For study and knowledge issues, how could I clean a setInterval and then according to some event I can continue to run it again.

'use strict';

    var imgAtual = 0;
    var arrImg = ['images/relatorio.jpg', 'images/clp.jpg', 'images/estudo-viabilidade.jpg', 'images/padrao.jpg'];

    function mudarImagem(){
        var imgElm = document.querySelector('.img-slide');
        if(imgAtual < arrImg.length){
            imgElm.setAttribute('src',arrImg[imgAtual]);
            imgAtual++;
            console.log(imgAtual);
        }else{
            imgAtual = 0;
            imgElm.setAttribute('src',arrImg[imgAtual]);
            imgAtual++;
        }

        imgElm.addEventListener('click',function(){
            clearInterval(mudando);
        })

    }



    var mudando = setInterval(function(){
        mudarImagem();
    },1000);
    
asked by anonymous 09.07.2015 / 01:59

1 answer

1

Talk to me,

If I understand your question right, you want something like a " pause () " and then give it a " play () " again. Well, for setInterval this does not exist natively. It will depend on you to create a structure that can handle that.

I advise something like this:

var SimpleSlider = {
    loopTimer : null, //variável de controle para o setInterval

    loop: function(){ //função que faz o loop
        var me = this;  //referencia para o contexto do SimpleSlider 
        this.loopTimer = setInterval(function(){
           me.mudarImage();
        },3000); //Executa a transição a cada 3s
    },

    mudarImage : function(){
        console.log('Mudar imagem');
        //Aqui vem a lógica de transição de imagens
    },

    play : function(){
        this.mudarImage();
        this.loop(); 
    },
    pause : function(){
        clearInterval( this.loopTimer ); //"Pause". O clearInterval para tudo.
    }
};

To use, use a console like IE F12 or Chrome Developer Tools, paste the code and do:

SimpleSlider.play();  // espere as respostas
SimpleSlider.pause(); // as respostas vão parar de sair no console.

These functions can be in button events for example. Hope this helps! Hugs!

    
09.07.2015 / 13:29