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

Discovering additional element information while utilizing the 'Sortable' feature

My Current Objective: In my setup, I have a 'calendar' comprising 5 columns, each column containing 5 separate divs known as timeslots. The main purpose here is to show appointments in these specific timeslots and utilize JQuery's Sortable ...

Using JQUERY, CodeMirror adds elements to the HTML editor

I have been utilizing CodeMirror for my project, specifically the "HTML Editor With Preview" module. To test its functionality, I created a fiddle: --> http://jsfiddle.net/Vu33n/6/ While I successfully got the editor to work, I am currently facing an iss ...

Setting fixed width for table headers in Bootstrap 3

Can someone explain why the width of "th" is not fixed and new line breaks occur when the content is too big? Currently, the "th" width expands. How can this be fixed? The width of my first column is col-lg-2. Click here for an example image ...

When attempting to transfer data from the parent component to child components, the data is appearing as undefined in the display

I have been working on passing data from a parent component to child components, but I keep encountering an issue where the data is showing as undefined. Below is the code snippet: Parent Component In this section, I have declared the variable part_data ...

Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using: function tblnewrow() { var newrow = ' ...

Upgrading the entire document's content using jQuery

I am dealing with an ajax response that provides the complete HTML structure of a webpage, as shown below: <!DOCTYPE> <html> <head> <!-- head content --> </head> <body> <!-- body content --> </b ...

The AngularJS modal is sending back the results before updating the parent scope

When launching a modal from my web page, I am updating an array passed from the parent. However, when closing the modal and sending back the updated results, the parent scope object is also being updated. If the user decides not to update and cancels the ...

Vue does not consistently update HTML when the reference value changes

I am trying to showcase the readyState of a WebSocket connection by utilizing a Ref<number> property within an object and displaying the Ref in a template. The value of the Ref is modified during WebSocket open and close events. However, I am encount ...

The issue with updating the menu class in Internet Explorer 8 is not being resolved

Here is a code snippet using JavaScript: var x = jQuery(window).innerHeight(); jQuery(document).scroll(function() { if (jQuery(this).scrollTop() >= x) { jQuery('#nav').removeClass('nav').addClass('topfix_nav'); ...

ensure that html tags display properly when retrieved from json in an angular directive template

Trying to embed ruby tags in a directive template but struggling with escaping them. Despite reading about $sce and filters, the confusion deepens as browser tabs multiply. The directive code is as follows: angular.module("ngFlashCard", ["ngSanitize"]).d ...

The system does not acknowledge "ENVIRONMENT" as a command that can be executed either internally or externally, or as a batch file that can be

While running my Next.js application, I encountered the following error in a script: "scripts": { "dev: "ENVIRONMENT=env/.env.development next dev", "check": "npm run format && npm run eslint", "e ...

Conceal All Other Divs upon Clicking on a New Div Bearing the Identical Class

I'm having trouble implementing the feature that closes other divs when I click on a new div with the same class. It seems like it should be straightforward, but for some reason, it's not working for me. Here is the link to the fiddle where I&apo ...

Error occurs in ReactJS App when the state is updated in Redux only after dispatching the same action twice

Check out the following code snippet: ChartActions.js import * as types from './ChartTypes.js'; export function chartData(check){ return { type: types.CHART_DATA,check }; } ChartTypes.js export const CHART_DATA = 'CHART_DATA ...

Retrieving the class name using jQuery

In my HTML code, there is a div with three classes defined as: <div class = "a b c"> .. </div> My goal is to access only the class b using the .attr() method. Is this achievable? ...

The tension settings in Chart.JS appear unusual

I recently updated to ChartJS v4.0.1 and noticed a new option called tension for curving the line chart. However, I'm not satisfied with how it looks. The tension option ranges from 0 to 1, and I've experimented with different values to enhance ...

Dealing with AJAX error in pure JavaScript

I have been attempting to address AJAX errors using the code below, but unfortunately, it does not seem to be effective. function ajaxPost(url, data, success, error) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () ...

The user_login view in the account views did not provide an HttpResponse object, but instead returned None

Error: Unable to register or log in - account.views not returning HTTP response # accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, Use ...

Setting the default type of an array in props in Vue 2 is a common need for many developers

My Vue component relies on an array of objects as a prop and I always make use of prop validation, especially for setting default values. In this case, my current setup is: props: { items: Array } However, I would prefer it to resemble something lik ...

In Node.js, the mongodb+srv URI does not support including a port number

Currently, I am working on a project in nodejs using express js. I have encountered the following error: MongoDB connection error: MongoParseError: MongoDB+srv URI cannot contain a port number. In my "MongoDB Atlas" dashboard, I have obtained my "connecti ...

Combining divs with identical values in Angular

I am working on creating my very own custom Calendar. Take a look at the full example of my component here I need help figuring out how to combine week divs that share the same value {{day.weekNumber}} so that there is only one div for each shared value, ...