Tips for adjusting the time interval on an automatic slideshow when manual controls are in play

I'm having trouble with my slideshow. I want it to run automatically and also have manual controls, but there are some issues. When I try to manually control the slides, it takes me to the wrong slide and messes up the timing for the next few slides. Does anyone have a solution?

I've attempted changing the slideIndex to 0, but that just takes me back to the first slide instead of advancing to the next one.

  
    var slideIndex = 0;
    showSlides(slideIndex);

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

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

    // rest of the JavaScript code...

   
     * {box-sizing: border-box;}
      // CSS styles...

  
    
    < h2>Automatic Slideshow</h2>
    < p>Change image every 10 seconds:</p>

    // HTML markup...
  

The expected interval is 10 seconds, but it's only a couple of seconds. The next/previous slide buttons aren't functioning as expected either.

Answer №1

It seems the issue lies in how timeouts are set for your slideshow buttons. Pressing next or previous doesn't cancel old timeouts, causing multiple slides to transition simultaneously within the desired time frame.

To resolve this, consider using intervals instead of individual timeouts and managing them outside functions.

Upon user input (forward/back), clear the current interval and create a new one to prevent overlapping transitions and ensure smooth carousel movement.

JAVASCRIPT

let slideIndex = 0;
const slideTime = 5000;
let slideInterval = setInterval(() => changeSlide(true), slideTime);

function jumpSlide(forward) {
  clearInterval(slideInterval);
  changeSlide(forward)
  slideInterval = setInterval(() => changeSlide(true), slideTime);
}

function changeSlide(forward) {
  const slides = document.getElementsByClassName('slide');
  slides[slideIndex].classList.remove('active');
  if (forward) {
   if (slideIndex + 1 > slides.length - 1) {
    slides[0].classList.add('active');
    slideIndex = 0;
  } else {
    slides[slideIndex + 1].classList.add('active');
    slideIndex ++;
  } 
  } else {
    if (slideIndex - 1 < 0) {
    slides[slides.length - 1].classList.add('active');
    slideIndex = slides.length - 1;
  } else {
    slides[slideIndex - 1].classList.add('active');
    slideIndex --;
  }
  }
}

HTML

<div class='slide-container'>
<div class='slide active'></div>
<div class='slide'></div>
<div class='slide'></div>
</div>
<button onclick='jumpSlide(false)'>last slide</button>
<button onclick='jumpSlide(true)'>next slide</button>

CSS

.slide-container{
  display: flex;
}
.slide {
  width: 50px;
  height: 50px;
  background-color: rgba(0, 0, 0, 0.25)
}
.active {
  background-color: red;
}

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

When the clearInterval function is invoked - either when the timer is modified or when the rendering is detached from the setInterval it is linked to

As a new React developer, I've come across a problem that has me stuck. Does the setInterval associated with a specific render get cleared automatically? import React, { useState, useEffect, useRef } from "react"; import ReactDOM from ...

Images that dynamically adjust within the confines of a single div

My issue involves a simple script that includes two responsive images. When the window is minimized, the images adjust accordingly. However, when I place both images within the same div like this: <div class="wrapper"> <div class="block"&g ...

Build a home page in HTML with full width design

My webpage currently allows scrolling to the right and left in HTML. I would like to change this functionality. What I envision is having my cup and book visible without the need for scrolling, with a background image centered on the page. <div cla ...

Exploring the Interaction of Users with HTML Table Cell <td>

I am currently analyzing the code for a web page. Within this code, users have the ability to double-click on a cell in a table (<td> as shown below) and input a value. Is there a specific attribute or element within this HTML that indicates user in ...

Best practices for displaying a Multidimensional JSON Object using JavaScript

Within my current project, I have a JSON object structured as follows: { "face": [ { "attribute": { "age": { "range": 5, "value": 35 }, "gender": { "confidence ...

The submission of an Angular form results in errors such as being unavailable or

After building a registration page component in Angular and following tutorials, I encountered a frustrating bug. When pressing the submit button on the form, the console would display "undefined" when attempting to access the NgForm's value. However, ...

Tips on changing the outline color by clicking

I'm working on a simple code where I need to change the outline color when a user clicks on a text field. <input type="text" id="box1" /> <input type="password" id="box2" /> <input type="email" id="box3" /> <input type="submit" ...

Sending form data to a CFC asynchronously in Coldfusion

To begin with, I want to mention that the product I am creating is intended for individuals who do not have automatic access to HTML5. Some of these people are still using IE8. Here's an example of a form: <form action="ee.cfc?method=xlsupload" en ...

The Shopify cart.json request has encountered a setback with error 330

My current task involves using jQuery to retrieve cart data from Shopify, which I then display on another website. However, this process has suddenly stopped working. When I attempt to make the request in Google Chrome, it shows as 'failed' and u ...

Having trouble with Jquery Ajax call in IE8?

I have a dynamic data loading from the database, with each row containing links that perform various actions. Most of them work perfectly fine, but I've noticed an issue with the last one I added – it doesn't seem to be functioning properly on ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

How to trigger a file download instead of opening it in a new tab when clicking on a txt or png file in AngularJS

After retrieving my file URL from the backend API, I am trying to enable downloading when the user clicks a button. Currently, the download function works smoothly for Excel files (`.xlsx`), but for text (`.txt`) files or images (`.jpeg`, `.png`), it only ...

Top method for utilizing overlays

Is there a method to randomly select hex codes for specific colors? I want to replicate the design in this image through coding. Image Here is the code I have so far: HTML <div id="group"> <div class="sub red panel"> </div><!--su ...

Is it possible to add a border to both the tbody and td

I currently have a table that is organized with tbody elements to group rows together. In order to create a grid-like structure, I applied borders to each individual td element within the tbody. However, I also desire to show that the tbodies themselves ar ...

Is it possible to use PHP to add a prefix to every selector in a snippet of CSS code?

Suppose I have a variable named $css that holds some CSS code. My goal is to prepend a specific text to each selector. For instance, consider the following CSS code: #hello, .class{width:1px;height:1px;background-color:#AAA;} div{font-size:1px} input, a, ...

The TypeScript error message states that a value of 'undefined' cannot be assigned to a type that expects either a boolean, Connection

I've been grappling with this code snippet for a while now. It was originally written in JavaScript a few months back, but recently I decided to delve into TypeScript. However, I'm struggling to understand how data types are properly defined in T ...

text box with an immobile header

As the browser window size decreases, the layout changes. However, when scrolling down, the search text box moves up and is no longer visible due to its lack of fixation. How can I make the search text box stay fixed as I scroll down? I tried implementing ...

Unable to locate the module model in sequelize

Having some trouble setting up a basic connection between Postgres and SQL using Sequelize. I keep getting an error where I can't require the model folder, even though in this tutorial he manages to require the model folder and add it to the sync, lik ...

The scroll animation feature was not functioning properly in Next.js, however, it was working flawlessly in create react app

I recently transitioned a small project from Create React App (CRA) to Next.js. Everything is working as expected except for the scroll animations in Next.js, which are not functioning properly. There are no errors thrown; the animations simply do not occ ...

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...