Search code examples
javascriptfunctionif-statementonmouseover

How to set a if else function with onmouseover and onmouseout event on a setInterval with images?


var myImage = document.getElementById("mainImage");

var imageArray = ["_images/1.jpg","_images/2.jpg","_images/3.jpg",
                  "_images/4.jpg","_images/5.jpg","_images/6.jpg"];

var imageIndex = 0;

function changeImage() {
    myImage.setAttribute("src", imageArray[imageIndex]);
    imageIndex++;
    if (imageIndex >= imageArray.length) {
        imageIndex = 0;
    }
}

I'm learning fundamental in JS how to get a changing images like a gif, when you onmouseover it, it will stop, then onmouseout, it resume again. I'm struggling on the below part.

var intervalHandler = setInterval(changeImage, 3000);

myImage.onmouseover = function(){
    clearInterval(intervalHandler);
}

myImage.onmouseout = function(){
    setInterval(changeImage, 3000);
}

Solution

  • This is where you got your example? http://www.w3schools.com/jsref/met_win_cleartimeout.asp

    To do it properly:

    //Start initially:
    var intervalHandler = setTimeout(changeImage, 3000);
    
    myImage.onmouseover = function(){
        clearInterval(intervalHandler);
    }
    
    myImage.onmouseout = function(){
        //reset the variable, so it has the new timeout.
        intervalHandler = setInterval(changeImage, 3000);
    }
    

    Make sure your setInterval function returns the timeout:

    function clearInterval(timeout, period){
       return clearTimeout(callback,period);
    }
    
    function myStopFunction(timeout) {
        clearTimeout(timeout);
    }
    

    Btw to make sure you loop indefinitely you want to execute:

    intervalHandler = setTimeout(changeImage, 3000);
    

    at the end of your changeImage function.