Home » Code editor » How to display loop-images by JavaScript

How to display loop-images by JavaScript


#imageContainer {width: 300px;height: 300px;}        
img {width: 100%;height: 100%;}     


<div id="imageContainer"> 
   <img id="loopingImage" src="" alt="Image Loop"> 


// Array of image URLs
const images = [

let currentIndex = 0;

// Function to change the image
function changeImage() {
	const imgElement = document.getElementById('loopingImage');
	imgElement.src = images[currentIndex];
	currentIndex = (currentIndex + 1) % images.length;

// Change the image every 1 second
setInterval(changeImage, 1000);

// Initialize with the first image

This example includes:

  • An array of image URLs (images).
  • A function (changeImage) that updates the src attribute of the img element to display the current image and then increments the index.The setInterval function that calls changeImage every 1000 milliseconds (1 second).
  • Initialization of the first image when the page loads.
  • Replace ‘loop1.jpg’, ‘loop2.jpg, etc., with the actual paths or URLs to your images. This script will cycle through the images in the array every second.

Github & Pencode


Get Giveaway every day!

Check Also

Understanding User Interactions: A Customer Journey Map Example

In the realm of strategic business tools, the customer journey map stands tall as a …

IOS update

Fix iPhone Activation Issue after iOS 17 Update

The experience of owning Apple’s flagship device, which is known for its strong security measures …