Home > Mobile >  how to change image for every 4 seconds in javascript?
how to change image for every 4 seconds in javascript?

Time:11-01

i want to change image i have done code still image is not showing at all. file not found error is showing i want to change image every 4 seconds how can i do that? please help

<html lang="en">
<head>
   
    <title>sliding image</title>
</head>
<body onload="f1()">
    <img id="img1" src=""alt="" width="200px">
    <script>
       let arr=new Array();
        function image()
        {  
              let img2=document.getElementById("img1");
              x=0;
              arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png"
             img2.src=arr[x];
              x=1;
              arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg"
              img2.src=arr[x];
              x=2;
              arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
              img2.src=arr[x];
              x=0;
        }
        function f1()
        {
             window.setInterval(image,4000);
        }
    </script>
</body>
</html>

CodePudding user response:

The images have the names 1.jpg, 2.jpg and 3.jpg and are in the same folder with test.html and test.js file. U can switch the timeout in seconds.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
   <script src="test.js" type="text/javascript" defer></script>
</head>
<body>
   <img id="imageSwitcher" src="" alt="">
</body>
</html>
"use strict";

const imageArray = ["1.jpg", "2.jpg", "3.jpg"];
const imageSwitcher = document.getElementById("imageSwitcher");

let timeout = 4;
let i = 0;
setInterval(() => {
   imageSwitcher.src=imageArray[i];
   console.log(i);
   i  ;
   if (i >= imageArray.length) {
      i = 0;
   }
}, timeout * 1000);

CodePudding user response:

You have to increment the pointer and reset it like below code.

<script>

    var pointer = 0;

    var imageArray = [
        "C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png",
        "C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg",
        "C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
    ];


    function image()
    {  
      
          let img2 = document.getElementById("img1");
          
          img2.src = imageArray[pointer];

          pointer  ;

          // reset the pointer if hit the max
          if (pointer == imageArray.length-1){
            pointer = 0;
          }

    }
    function f1()
    {
         window.setInterval(image,4000);
    }
</script>
  • Related