setInterval how to come back again after giving a clearInterval?

Asked

Viewed 678 times

0

for reasons of study and knowledge, how could I clear a setInterval and then according to some event I can continue its execution 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);
  • @Marconi I want to return with the execution of setInterval after I have already paralyzed her with a clearInterval.

1 answer

1

Speak my,

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

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. I hope I helped! Hugs!

Browser other questions tagged

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