Creating an image slideshow with a looping JavaScript array: Step-by-step guide

One issue with the program is that when it runs, only the last array value image is displaying on the screen while the other images are not.

Below is the HTML code:

<img id="mg" alt="image not found">

And here is the JavaScript code:

var images=["image", "image2","img","imag"]
test();
function test(){
   var index = 0;
   for(var count=0; count<images.length; count++){
       document.getElementById('mg').src = images[count] + ".jpg";
       document.getElementById("mg").width = "500";
       document.getElementById("mg").height = "300";
       index = index + 1;
       setTimeout(test, 1000);
       if(index + 1 > images.length){
            index = 0;
            count = 0;
    }
   }
}

Answer №1

function test(){
   var index = 0;
   for(var count=0; count<images.length; count++){
       ...
       setTimeout(test, 1000);
       ...
   }
}

setTimeout() in this context operates differently than expected. It does not create a delay before moving on to the next step. Instead, it instructs the engine to pause for 1,000 milliseconds independently while the remaining code continues execution.

To approach this more effectively, consider the following alternative:

const imageUrls = [
  'first.jpg',
  'second.jpg',
  'third.jpg',
  'fourth.jpg'
];

const imgEl = document.querySelector('img');
imgEl.src = imageUrls[0];

function advanceImage() {
  imgEl.src = imageUrls[imageUrls.indexOf(imgEl.src) + 1] || imageUrls[0];
}

setInterval(advanceImage, 1000);

In this revised method, the image is initially set to the first URL. Then, every second, the current index is determined and incremented by one. If the end of the array is reached, the display reverts to the initial image URL.

An ideal solution would involve handling this functionality with CSS rather than JavaScript, but I wanted to offer this example nonetheless.

Answer №2

Is the loop necessary? Alternatively, you can try the following approach:
<html>
    <head>
    </head>
    <body>
        <img id="mg" alt="image not found"> 
        <script type="text/javascript>
        var images=["image", "image2","img","imag"]
        test();

        var count = 0;

        function test(){
                console.log("Executing with current count: " + count);

               document.getElementById('mg').src = images[count] + ".jpg";
               document.getElementById("mg").width = "500";
               document.getElementById("mg").height = "300";

               if(count + 1 >= images.length){
                    count = 0;
                }
                else
                {
                    ++count;
                }
        }

        setInterval(test, 1000);

        </script>       
    </body>
</html>

The setInterval function ensures that the test function is called every second. By keeping the counter outside the function, it remains accessible and allows for easy retrieval of elements in the array.

Answer №3

To optimize your test function, you don't have to iterate through all the images every time. Instead, you can keep track of the current index outside the function and update it with each execution. Here's a simple example:

var images = ["https://api.example.com/img/1", "https://api.example.com/img/2", "https://api.example.com/img/3", "https://api.example.com/img/4"]

var currentIndex = 0;

testFunction();

function testFunction() {
  // Update the image source
  document.getElementById('img').src = images[currentIndex] + ".jpg";
  document.getElementById("img").width = "100";
  document.getElementById("img").height = "100";

  // Update the index for the next iteration
  currentIndex++;
  if (currentIndex === images.length) {
    currentIndex = 0;
  }

  // Set timeout for the next iteration
  setTimeout(testFunction, 1000);
}
<img id="img" alt="image not found">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Set a div to have both absolute positioning and sticky behavior

Looking to create a div ("profilemenu") that pops out on the right side of the page triggered by a button (I'll handle this part). I want it to have a sticky attribute, but positioning has been tricky. Using position: absolute works for proper placeme ...

Having trouble with the collapse feature on my DataList cards

I have a sample card and a DataList on my webpage. The collapse functionality is functioning correctly on the example card, but I am unable to get it to work on the actual cards. Below is the code snippet for reference: <div class="resultadosEspe ...

Incorporate a local asciinema file into an HTML document

Is there a way to embed a local asciinema session into an html file? Here is how my directory is structured: $ tree . ├── asciinema │ └── demo.cast ├── css │ └── asciinema-player.css ├── index.html ├── js │ ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...

Using a CSS nth-child selector to eliminate the bottom margin of the final row

As I work on creating lists that are displayed in columns of two, each .customer-review-container includes a margin-bottom CSS property like this: <div class="col-md-6"> <div class="customer-review-container"> </div> <!-- en ...

Choose options from the month dropdown menu using Selenium WebDriver

Presently focused on working with Selenium WebDriver and Java. I am attempting to pick an option from a date picker form. When trying to select the month from the dropdown of the date picker, an error is displayed stating Unable to locate element: {"method ...

What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning? var d = new D ...

Tips for implementing conditional app.use() in nestJS backend strategies?

Trying to incorporate helmet into my nestJS application. I also require the inclusion of graphqlUploadExpress. How can I properly utilize the usesUpload condition to implement either helmet alone or along with upload? import { NestFactory } from '@nes ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Is it possible to utilize AJAX requests in order to create a marker on google maps that updates in real-time?

My goal is to develop an app that generates a real-time updating google map, and I have been advised that AJAX requests can help achieve this. Nevertheless, after studying the documentation, I am uncertain about how to apply this method to solve my issue ...

What is the best way to utilize "require" dynamically in JavaScript?

Within the "sample.js" file, there is a JavaScript function structured as follows: var mapDict = { '100': 'test_100.js', '200': 'test_200_API.js', '300': 'test_300_API.js' } function mapAPI() { ...

Tips for creating 2 fetch methods for a contact API and a Message API in ReactJS!

I am just starting to learn reactjs and have been able to successfully map data from a JSON API. My goal now is to ensure that when a number is saved in the contact list, it should also display the name in the message list. To achieve this, I plan to creat ...

Round progress indicator with directional pointer

I've been working on creating a round progress bar that features an arrow at the front. This is my current progress: HTML Code: <!-- Container --> <ul class="progress"> <!-- Item --> <li data-name="Item 1& ...

Get data from a JSON file using JavaScript

Dealing with a rather intricate and detailed JSON structure, I have a specific extraction task at hand. The goal is to retrieve information (text) from the JSON only if the resource-id includes the text "com.shazam.android:id/" and certain prope ...

Create visual representations using the data displayed in charts generated by Chart JS

Good evening. I am currently utilizing Chart JS in my project to visualize the total count per column in a bar graph. My backend framework is Laravel, and I pass the data from the controller using the variable $datacount. This snippet shows the query in ...

Angular prevents the page from reloading when using `$window.location`

I'm facing an issue while trying to refresh my admin page using Angular. I've come across $window.location.reload() and $route.reload(). I attempted to use $window.location.reload() by injecting $window into the function parameters. scope.uploadL ...

Run a JavaScript function in the webpage that is being loaded using an XMLHttpRequest

What is the best way to trigger a JavaScript function within a specific page using XMLHttpRequest? For example, if I have the following code: xmlhttp.open("GET", "page1.php?q=" + mydata, true); How can I execute a JavaScript function that will, for insta ...

Measuring the space between components

I am looking for a way to dynamically calculate distance on a canvas, similar to the example shown in the figure. I want to be able to drag the highlighted joints in order to adjust the span for calculating distances. Are there any plugins available for th ...

Ajax seems to be interacting with an empty session variable

I am facing some issues with a piece of code that I've written. Here's the function in question from my PHP class: public function generalSettings(){ $totalPrice = 0; foreach($_SESSION['items'] as $key => $value){ ...