setInterval does not work after clearInterval

3

I'm making a slider where, by placing the mouse over, I want the interval to stop. This part works perfectly with clearInterval. However, when the mouse exits, setInterval is not working. I can get the mouse output event perfectly (I used tests giving an alert when the mouse exits, for example), but setInterval does not work. The code is as follows:

JS:

function slideImgs(){
    var sld = document.querySelector("#slider");
    var imgs = document.querySelector("#slider").getElementsByTagName("img");
    var i = 0;
    var pos = 82.1;
    var maxLoop = pos * imgs.length;

    var interval = setInterval(function(){
        while(pos <= maxLoop){
            sld.style.transform = "translateX(-"+pos+"rem)";
            pos = pos + 82.1;

            if(pos >= maxLoop){
                pos = 0;
            }

            break;
        }

    },2000);

    sld.onmouseover = function(){
        clearInterval(interval);
    }

    sld.onmouseout = function(){
        setInterval(interval,2000);
    }
}

HTML:

<div id="slides">
    <span id="nav1"> < </span>
    <span id="nav2"> > </span>
    <ul id="slider">
        <li><img src="img/img1.jpg" class="slides"/></li>
        <li><img src="img/img2.jpg" class="slides"/></li>
        <li><img src="img/img3.jpg" class="slides"/></li>
        <li><img src="img/img4.jpg" class="slides"/></li>
    </ul>
</div>
    
asked by anonymous 28.02.2016 / 00:01

1 answer

3

The setInterval(interval,2000) call will not do anything. The interval is an "identervalID" but setInterval expects a callback as a parameter.

link
link

Give your callback a name:

//pense num nome melhor que esse :)
function mexerNasCoisas(){
    while(pos <= maxLoop){
        sld.style.transform = "translateX(-"+pos+"rem)";
        pos = pos + 82.1;

        if(pos >= maxLoop){
            pos = 0;
        }

        break;
    }

}


var interval = setInterval(mexerNasCoisas,2000);

sld.onmouseover = function(){
    clearInterval(interval);
}

sld.onmouseout = function(){
    interval = setInterval(mexerNasCoisas,2000);
}

Another possibility is to simply leave the interval running at all times, without giving clearInterval. You can disable the interval by setting a flag.

var isActive = true;

var interval = setInterval(function(){
    if(!isActive){ return; }

    while(pos <= maxLoop){
        sld.style.transform = "translateX(-"+pos+"rem)";
        pos = pos + 82.1;

        if(pos >= maxLoop){
            pos = 0;
        }

        break;
    }

},2000);

sld.onmouseover = function(){
    isActive = false;
}

sld.onmouseout = function(){
    isActive = true;
}
    
28.02.2016 / 00:17