Search code examples
javascripthtmlsetintervalonmouseover

how to make an image change multiple times onmouseover


I'm trying to make an image change multiple times so i used setInterval but it doesn't stop

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
  </head>
  <body>
    <a href="https://www.google.com" target="_blank">
      <img onmouseover="setInterval(mouseOver,500)" onmouseout="mouseOut()" id="a" src="1.jpg" style="height: 45vh; width: 23vw;">
    </a>
    <script>
      function mouseOver()
      {
        element=document.getElementById("a")
        if (element.src.match("pic_bulboff.jpg"))
        {
          document.getElementById("a").src="8.jpg";
        }
        else if (element.src.match("8.jpg"))
        {
          document.getElementById("a").src="6.jpg";
        }
        else
        {
          document.getElementById("a").src="1.jpg";
        }
      }
      function mouseOut()
      {
        document.getElementById("a").src="1.jpg";
      }
    </script>
  </body>
</html>


Solution

  • Use clearInterval and track the initial interval:

    <!DOCTYPE html>
    <html>
    
    <head>
      <meta charset="utf-8">
      <title>Untitled Document</title>
    </head>
    
    <body>
      <a href="https://www.google.com" target="_blank">
        <img onmouseover="init()" onmouseout="mouseOut()" id="a" src="http://placecage.com/400/400" style="height: 45vh; width: 23vw;">
      </a>
      <script>
        var interval;
    
        function init() {
          interval = setInterval(mouseOver, 500)
        }
    
        function mouseOver() {
          element = document.getElementById("a")
          if (element.src.match("400/400")) {
            document.getElementById("a").src = "http://placecage.com/300/300";
          } else if (element.src.match("300/300")) {
            document.getElementById("a").src = "http://placecage.com/200/200";
          } else {
            document.getElementById("a").src = "http://placecage.com/500/500";
          }
        }
    
        function mouseOut() {
          document.getElementById("a").src = "http://placecage.com/400/400";
          clearInterval(interval)
        }
      </script>
    </body>
    
    </html>