The setInterval function for the automated image slider is experiencing issues and is not functioning properly

I am facing an issue where the third photo in the slider does not appear initially. Eventually, the slide fails completely, causing the photos to change rapidly. Strangely, after the slide fails, the third photo sometimes appears sporadically. I am puzzled as to why this happens and how to fix it. Can you offer any solutions?

let sliderImages = document.querySelectorAll(".slide");
current = 0;

function reset() {
  for(let i = 0; i < sliderImages.length; i++) {
    sliderImages[i].style.display = "none";
  }
}

function startSlide() {
  reset();
  if(current == sliderImages.length) {
    current = 0;
  }  
  sliderImages[current].style.display = "block";
  current++;
  setInterval(startSlide, 2000);
}

startSlide();
body, #slider, .wrap, .slide-content {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100vh;
  overflow-x: hidden;
}

.wrap {
  position: relative;
}

.slide {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.slide1 {
  background-image:   url("https://images.pexels.com/photos/3153198/pexels-photo-3153198.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
}

.slide2 {
  background-image: url("https://images.pexels.com/photos/3153208/pexels-photo-3153208.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260")
}

.slide3 {
  background-image: url("https://images.pexels.com/photos/1036641/pexels-photo-1036641.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260")
}
<div class="wrap">
  <div id="slider">
    <div class="slide slide1">
      <div class="slide-content">
      
      </div>
    </div>
    <div class="slide slide2">
      <div class="slide-content">
      
      </div>
    </div>
    <div class="slide slide3">
      <div class="slide-content">
      
      </div>
    </div>
  </div>
</div>

Answer №1

The issue you are facing is that every time the function runs, a new interval is being set, leading to multiple intervals running simultaneously. To solve this, you only need to set the interval once, and then the function will be called every two seconds as intended. Here is the modified version of your code:

let sliderImages = document.querySelectorAll(".slide");
current = 0;

function reset() {
  for(let i = 0; i < sliderImages.length; i++) {
    sliderImages[i].style.display = "none";
  }
}

function startSlide() {
  reset();
  if(current == sliderImages.length) {
    current = 0;
  }  
  sliderImages[current].style.display = "block";
  current++;
}

setInterval(startSlide, 2000);
body, #slider, .wrap, .slide-content {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100vh;
  overflow-x: hidden;
}

.wrap {
  position: relative;
}

.slide {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.slide1 {
  background-image:   url("https://images.pexels.com/photos/3153198/pexels-photo-3153198.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260");
}

.slide2 {
  background-image: url("https://images.pexels.com/photos/3153208/pexels-photo-3153208.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260")
}

.slide3 {
  background-image: url("https://images.pexels.com/photos/1036641/pexels-photo-1036641.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260")
}
<div class="wrap">
  <div id="slider">
    <div class="slide slide1">
      <div class="slide-content">
      
      </div>
    </div>
    <div class="slide slide2">
      <div class="slide-content">
      
      </div>
    </div>
    <div class="slide slide3">
      <div class="slide-content">
      
      </div>
    </div>
  </div>
</div>

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

Looking for assistance with aligning UL elements in CSS using absolute positioning for a dropdown effect

I'm currently working on implementing a language switching feature on this website. The concept involves using a SPAN element that reveals a dropdown box (based on UL) containing a list of available languages when hovered over. Below is a preview of t ...

Guide to presenting a personalized date format in an Angular table by utilizing the gantt-tooltip attribute

How can I customize the date format displayed in the tooltip to only show the month and day (e.g. Sep 01) within an Angular Gantt table? Currently, the date is being shown in the default format "MMM DD, HH:mm". Can anyone assist me in resolving this issue ...

At times, Mongoose may return null, while other times it returns data frequently

I have designed a unique mongoose schema for managing contacts, with a custom defined ID. Here is the schema structure: const mongooseSchema = new mongoose.Schema({ _id:{ type:String, unique:true, required:true }, firstN ...

Developing a Generic API Invocation Function

I'm currently working on a function that has the capability to call multiple APIs while providing strong typing for each parameter: api - which represents the name of the API, route - the specific route within the 'api', and params - a JSON ...

NodeJS - Subtract one array from another, while keeping all duplicates in place

Although the title may be misleading, how can you achieve the following: a = [1, 2, 2, 3, 3, 3]; b = [1, 2, 3]; a.subtract(b); I am aiming for a result of [2, 3, 3] instead of an empty array, as seen in other similar solutions. I want to remove only the ...

The initialized Javascript array solely consists of undefined elements, without any of the expected values

I was under the impression that I knew how to declare JavaScript arrays, but in this particular script, I seem to be stuck in an infinite loop of undefined elements within the array. In my code, I define three arrays containing numbers—two with multiple ...

Tips for utilizing the selected option in the name attribute with Javascript or jQuery

I am looking to use the "selected" attribute in the option element based on the name attribute using JavaScript or jQuery. Essentially, I want the option with name="1" to be automatically selected when the page loads. I have attempted the following code, b ...

Ways to automatically divide lists into various div elements

Hey there! I currently have a list of categories on my page that is subject to change. I'm looking for assistance in creating a loop that will divide my lists into groups of 5 items per div. For example: foreach($categories as $cat) <label> ...

Formatting HTTP HTML response in Vue.js can be achieved by utilizing various methods and techniques

I have a WordPress site and I'm trying to fetch a specific post by its ID. Currently, the content is being displayed successfully, but it's also showing HTML tags in the main output. Here is an example: https://i.stack.imgur.com/f3pdq.png Code ...

Turned off jquery on a specific div in order to resolve compatibility problems with Vue.js

Currently, I am working on a Drupal project which includes JQuery in all pages. We have recently introduced Vue.js for creating dynamic components directly in the HTML pages (not for building a single-page application). However, we are facing an issue whe ...

Switching Tabs When a Button is Clicked

I am currently using a guide from the link provided to learn how to create tabs: http://www.w3schools.com/howto/howto_js_tabs.asp. function openTab(evt, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClass ...

Communication between different windows using Chrome

I am facing an issue with my HTML5 Framework where the debugger is not visible in fullscreen mode due to the canvas taking up the entire screen. I need a solution where the debugger can be opened in another tab or popup so it can be moved off to another mo ...

Compare object key and array in Javascript to create a new object

Can you aid me in achieving the following output by comparing var1 and var2, and obtaining the output based on var2 where the keys are provided in a string array? var1 = {a:1, b:2, c:3, d:4}; var2 = ['a', 'd']; The expected output is ...

Typescript's way of mocking fetch for testing purposes

I have a query regarding the following code snippet: import useCountry from './useCountry'; import { renderHook } from '@testing-library/react-hooks'; import { enableFetchMocks } from 'jest-fetch-mock'; enableFetchMocks(); i ...

Is it possible to customize the styling of certain fundamental MUI components using makeStyles?

:D This is my first time embarking on a project from the ground up using react and MUI. I've been curious if I have set it up correctly. My goal right now is to incorporate some styling using makeStyles for certain components provided by Material UI ...

What would be the best way to structure this workflow as a JavaScript data format?

I have a complex workflow that I need to represent as a JavaScript data structure. This workflow involves a series of questions and answers where the response to one question determines the next one asked. Here is a basic example of what this workflow migh ...

Creating a flexible image layout within a container with relative positioning

I attempted to create a basic slideshow with images sliding from right to left as an animation: let slides = document.querySelectorAll('.img-container'); let l = slides.length; let i = 0; setInterval(function(){ i = (i + 1) % l; if(i == 0){ f ...

Modifying the background color using highcharts.js

I am attempting to customize the background colors of a highcharts scatter plot. While I can easily change the color of a specific section using the code provided, my goal is to apply multiple colors to different ranges within the same plot. Specifically, ...

What is the best way to notify the user about the input in the textbox?

Imagine you have a button and an input field. How could you notify the user of what is in the input field when the button is pressed? Please provide a simple explanation of your code. ...

Modify the background of a Div element by selecting an alternate color palette

Here is my code that changes the background of a Div on select change from a dropdown. I believe there might be a more efficient way to achieve this. Can anyone provide recommendations? Thank you for taking a look. $(document).ready(function() { $(" ...