Having trouble passing multiple arrays as parameters into setTimeout to create a slideshow

I've been working on a project to create a basic slideshow with 3 rotating images that should restart as soon as the last one is displayed, with a 5000ms interval between each image.

<div id="slideshow">&nbsp;</div>

<script type="text/javascript">
var imageArray = ['Image1','Image2','Image3'];
var currentIndex = 0;

nextPic = function(currentIndex,slideshow) {

  var theHTML = '<img src="http://www.domain.com/Pics/Test-' + imageArray[currentIndex] + '.jpg">';
  document.getElementById("slideshow").innerHTML = theHTML;

  if (currentIndex < imageArray.length) {
      currentIndex = currentIndex + 1;
  }
    else {
      currentIndex = 0;
    }

  setTimeout("nextPic(" + currentIndex + ")", 5000);
}

nextPic(currentIndex, "slideshow");

</script>

Despite trying various versions of Javascript code, I keep encountering the same issue: after displaying the last image (Test-Image3.jpg), an attempt is made to display an undefined image ("Test-undefined.jpg") before resetting back to the first image. Everything works perfectly except for this hiccup, and it's quite frustrating.

Answer №1

It is important to consider that when adding one to the current index, it should be done after checking against the array length:

if (currentIndex < imageArray.length - 1) {
  currentIndex = currentIndex + 1;
}
else {
  currentIndex = 0;
}

Alternatively:

currentIndex += 1;
if (currentIndex >= imageArray.length)
  currentIndex = 0;

There is actually no need to pass the parameter at all because the function can directly access the global variable. While it would be ideal not to have a global variable, if you already do, it might as well be utilized.

Answer №2

Modify to:

  if (counter < totalArray.length - 1) {
      counter = counter + 1;
  }

This adjustment is necessary to prevent displaying an out-of-bounds index such as totalArray[totalArray.length].

Furthermore, instead of:

counter = counter + 1;

You can simplify it by using:

counter ++;

Answer №3

An improved approach with setInterval():

const slideshow = function(){
   // Check if we have reached the end of the array, either replay or halt.
   if (currentIndex == images.length){
        currentIndex = 0; // Restart slideshow

   /* To stop the slideshow, include the following:
   *     window.clearInterval(slideshowInterval)     
   *     return false;
   */

   }
     let htmlContent = '<img src="http://www.mywebsite.com/Pics/' +    
                    images[currentIndex] + '.jpg">';
     document.getElementById("slideshow").innerHTML = htmlContent;
     currentIndex += 1;
}

const images = ['Image1','Image2','Image3'];
let currentIndex = 0;
let intervalSpeed = 5000;
let slideshowInterval = window.setInterval(slideshow, intervalSpeed); // Advance to next image every 5000 milliseconds

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

Error occurs when attempting to reference an object from an NPM package

Currently, I'm attempting to utilize the https://github.com/iamcal/js-emoji library for colon-to-emoji conversion. Following the installation of its NPM package, I included <script src="../node_modules/emoji-js/lib/emoji.js" type="te ...

Notifying asynchronous completion using Gulp, Babel, and configuration file config.yml

My current project involves using babel and gulp for handling tasks, as well as loading a yml config file for paths. This is the content of cofing.yml: PATHS: # Path to source folder sources: "jet/static/jet_src" # Path to dist folder dist: "jet/ ...

What is the method for modifying the chosen color using a select option tag instead of a list?

element, I have a Vue component that features images which change color upon clicking a list item associated with that color. <div class="product__machine-info__colors"> <ul> <li v-for="(color, index) in machine.content[0] ...

customizing highcharts title within a popup window

Is there a way to dynamically set the title of a Highcharts chart from an element? Check out my code snippet below: $(function () { var chart; $('#second-chart').highcharts({ chart: { type: 'bar' }, subtitle: { ...

Encapsulate ng-style within quotation marks

I am trying to hide a span if the value of filters[*index*] is empty. var span = "<span ng-style='{ 'display': filters[" + filterIndex + "] == '' ? 'none' : 'inline-block' }'></span>" cell.html ...

The navigation/hamburger icon vanishes after a click on a page link

I'm in the process of creating a single-page scrolling website. However, I am encountering an issue with the navigation bar. Specifically, when I click on a page link from the nav bar at screen widths less than 780px (when the hamburger icon appears), ...

When the page is refreshed, the JWT token mysteriously disappears from the header. How can this issue be resolved

I am currently using Jwt token based authentication with Angular 7 and node.js. When attempting to send a POST request with a Token to the server, everything works fine initially. However, upon reloading the page, I encounter an error on the server side. ...

How can I update a Django webpage using AJAX without having to refresh it?

I'm currently in the process of developing a messaging application and I'd like to implement a feature that automatically reloads the page every minute so users can see new messages without having to manually refresh. While I have some knowledge ...

What is the best way to make a request to the deployed API on Vercel?

Here is the structure of my files: root client index.js package-lock.json package.json routes.js Upon sending a request to my API, I receive a status code of 200 but an error message stating "You need to enable JavaScript to run this app." Both ...

Easy method for changing a value in an array using PHP if the index is known

In my PHP code, I have created an array of strings. Although my PHP knowledge may not be perfect, I understand that arrays are typically ordered by an index and can be accessed using array[0], array[1], etc. However, I have explicitly created an index for ...

JavaScript Subscribe / Unsubscribe Button

I am trying to create a simple JavaScript program that allows users to like and dislike content. However, I am new to JavaScript and finding it a bit challenging. Basically, when the user clicks on the Follow button, the "countF" variable should increase ...

The special function for switching elements within arrays of arrays may yield unpredictable results at certain indexes

Having an Array of Arrays, my Array is named splitarr [Array2[], Array1[], Array0[], Array3[]...]. Unfortunately, it is not ordered correctly from Index Zero to index 2. Therefore, I am seeking a way to rearrange splitarr so that it follows this order => ...

Tips for retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

The arrangement of a table, an iframe, and another table being showcased in close proximity

I need assistance in aligning a table, an iframe, and another table side by side without any breaks. Ideally, I would like all three elements to be centered on the page. It seems odd that they're not displaying next to each other as my screen is larg ...

Is it advisable to implement NumPy for handling 3D functions and matrices in Python code?

I am a beginner in Python and programming, currently exploring how arrays with internal relationships are typically managed. I experimented with creating a multiplication table using lists in both two and three dimensions, resulting in the following (for t ...

ordering an array based on a boolean property in TypeScript

I'm currently working with angular 10 and I need help figuring out how to sort this array: var dic = [ { state: false, id: 1 }, { state: true, id: 2} , { state: false, id: 3 }, { state: true, id: 4 }, { state: false, id: 5 } ] My goal is to ...

Searching for the coordinates of a specific value within a multidimensional array using MATLAB

I need help locating a specific value in a three-dimensional array and retrieving the three coordinates associated with it. For instance, let's say I have: B = [3 6 9; 12 15 18] B(:,:,2) = [5 8 11; 14 17 20] If I'm looking for the value 8, I ...

Guide on using webpack to import jQuery

When using webpack, is it necessary to install the jquery file from npm, or can I simply require the downloaded file from the jquery website? directory app/ ./assets/javascripts/article/create/base.js ./assets/javascripts/lib/jquery-1.11.1.min.js webpack ...

Comparable user interface on par with what we find on Windows Phone 7

I'm quite impressed with the innovative interface experience of Windows Phone 7. It stands out compared to other interfaces, whether on mobile devices, desktops, or the web. Despite its uniqueness, it remains highly usable. Overall, a great step in th ...

Performance issues with Three.js geometry merging

I am currently in the process of learning Three.js and have found the documentation to be a bit challenging to navigate due to the abundance of "todos" scattered throughout. My goal is to showcase anywhere from 50,000 to 500,000 red spheres on the screen. ...