setInterval does not work after clearInterval

Asked

Viewed 209 times

3

I’m doing a slider where, when placing the mouse over it, I want the interval to stop. This part works perfectly with clearInterval. However, when the mouse leaves, the setInterval is not working. I can pick up the output mouse event perfectly (I used tests giving an Alert when the mouse left, for example), but the 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>

1 answer

3


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

https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval

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 all the time, 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;
}
  • Complete and objective response. Thank you !

Browser other questions tagged

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