Time whizzes by too swiftly

After attempting to create an automated slideshow with clickable buttons, I encountered a problem. The slideshow functions properly, but as soon as I click one of the buttons, the slideshow speeds up significantly.

This is what I implemented in my attempt:

<script>
  var slideIndex = 0;
  showSlides(slideIndex);

  function plusSlides(n) {
    showSlides(slideIndex += n);
  }

  function currentSlide(n) {
    showSlides(slideIndex = n);
  }

  function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("button");

    for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
    }
    slideIndex++;

    if (slideIndex > slides.length) { slideIndex = 1 }

    for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
    }

    slides[slideIndex - 1].style.display = "block";
    dots[slideIndex - 1].className += " active";
    setTimeout(showSlides, 5000); // Change image every 10 seconds
  }
</script>

Can anyone explain why the slideshow becomes erratic when clicking on the buttons for specific slides?

Below is the HTML code used:

<div class="wrapper">
  <span class="button button1" onclick="currentSlide(0)"></span>
  <span class="button button2" onclick="currentSlide(1)"></span>
  <span class="button button3" onclick="currentSlide(2)"></span>
</div>

<!--Slideshow images-->
<div class="slideshow-container">
  <div class="mySlides Fade">
    <img src="homeScreen/teslaRoadster.jpg" style="width:100%">
    <div class="centered-text"> Customize Your Own Car</div>
    <button class="btnCustom">
      <a id="costumLink" href="#custom">Customize</a>
    </button>

  </div>

  <div class="mySlides Fade">
    <img src="homeScreen/modelXHomeScreen.jpg" style="width:100%">
    <div class="top-left"> MODEL X</div>
    <button class="btnModelX">
      <a id="costumLink" href="#modelx">Order Now</a>
    </button>
  </div>

  <div class="mySlides Fade">
    <img src="homeScreen/cybertruckHomeScreen.jpg" style="width:100%">
    <div class="centered-text">The Future Is Now</div>
    <button class="btnCyberTruck">
      <a id="costumLink" href="#cybertruck">Order Now</a>
    </button>
  </div>
</div>

Answer №1

When your showSlides() function is called, it initiates a timer which then triggers another call to showSlides(), creating a stack of function calls that execute one after the other.

To prevent this stacking behavior, it is essential to maintain a reference to the current timer and ensure that before starting a new timer, the previous one is stopped using clearTimeout(). The code snippet below demonstrates how this can be achieved, guaranteeing only one timer is active at any given time:

var timer = null; // Variable to store timer reference

function showSlides() {

  // Clear any existing timer
  clearTimeout(timer);

  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("button");

  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;

  if (slideIndex > slides.length) {slideIndex = 1}

  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }

  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  timer = setTimeout(showSlides, 5000); // Store updated timer reference
}

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

CSS: Achieving vertical centering without specifying a fixed height using line-height. Is it possible?

Using line-height to vertically center text within an inline-element is a technique I often employ. Here's a demo I created: body, section { width: 100%; } section { background-color: lightGrey; } #wrap { margin: 30px auto; width: 100%; ...

Is there a mistake in the way I am creating a horizontal navigation bar?

Currently working on creating a simple navigation bar using HTML/CSS for a Java/Spring Boot project. Admittedly, my HTML/CSS skills are quite limited as you can see below. I'm aware that there might be some mistakes in my approach. Thank you in advanc ...

An illustration of the fundamental concepts of require.js

main.md <markdown> <head> <script data-main="script" src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script> </head> <body></body> </markdown> script.css defi ...

Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use mom ...

A loop in JavaScript/TypeScript that runs precisely once every minute

Here is a snippet of my code: async run(minutesToRun: number): Promise<void> { await authenticate(); await this.stock.fillArray(); await subscribeToInstrument(this, this.orderBookId); await subscribeToOrderbook(this, this.orderBookId ...

Is it possible to obtain a return value from Electron's webContents.executeJavaScript when NodeIntegration is disabled?

Is there a way to retrieve a return value without using NodeIntegration in Electron, similar to ipcRenderer when it's enabled? ...

What is the best way to make this CSS arrow see-through?

My goal is to achieve this desired outcome: Currently, I have the following (focusing only on the left element for now): I am struggling to make the left arrow transparent and I can't seem to figure out how. This is the CSS Code I have so far: .ma ...

Issue with Google Maps iFrame not loading when utilizing JavaScript variables in the "src" attribute

Currently, I am facing an issue with utilizing JavaScript variables containing GPS latitude and longitude values in the "src" attribute of an iFrame in an HTML file for displaying image EXIF data on a Google Maps iFrame. When I hardcode specific latitude ...

Instructions for adding a new line in a textarea on Internet Explorer when reading from a file

I'm facing a situation where I need to display the contents of a file (let's call it abc.txt) in a textarea on a JSP page. However, when I try to do so, all the contents are displayed in one line without any line breaks or carriage returns. Inte ...

Can the geocoder API/search box be utilized to locate specific markers on a map?

Incorporating Mapbox into an Angular application with a high volume of markers on the map (potentially thousands) and hoping to implement a search box for users to easily locate specific markers based on unique names and coordinates. Is this functionalit ...

When a user right-clicks on certain words, the menu opens using JavaScript

Looking to implement a custom context menu that opens when specific words are right-clicked by the user in JavaScript. I have been searching for a solution for quite some time now. The word should be recognized based on an array of specific words. Can some ...

Extracting JSON Data into Text Boxes within jQuery UI Dialogs

Let me provide some context to my current issue. Due to the nature of the problem being work-related, I am unable to share much of the code. The task at hand involves working with a jQuery dialog. Essentially, I have a list of names displayed with a boots ...

Interact with one div to trigger changes in another (CSS)

I successfully influenced the style of one div when hovering over another div using the "+" selector, but I would prefer to find a different solution. My goal is for this interaction to work even if the .h div and the .t div are located in separate parent ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

Discover the method to adjust the position of elements, such as images, using radio buttons

I have an image positioned in a container along with 3 radio buttons. I want to make additional images appear over the main image when specific radio buttons are selected. Each button will trigger different positions for the additional images. So far, thi ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

React-select is failing to align properly with flexbox styling

I'm currently working on customizing my navbar to display both react-selects in a single row. I initially had everything running smoothly with the traditional vanilla select, but integrating the react-select caused my styling to break. Navbar.js impo ...

JavaScript - returning a false error

I'm experiencing an issue with my form validation function that is supposed to check for empty fields by looping through the form elements. Here's the code snippet: function validateForm(ourform){ var formElements = document.getElementById(our ...

Struggling to comprehend certain sections of code within AngularJS

I have been working through an AngularJS book to learn, but I am struggling with some code that is not well explained. The selectCategory() function is included in the ng-click directive like this: <a ng-click="selectCategory()">Home</a> < ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...