Can anyone provide instructions on incorporating a timer into carousel sliders using JavaScript?

I have a carousel sliders with text that I've customized using my own JavaScript. The carousel arrows work properly, but I want the sliders to automatically move after a set interval.

Here's the HTML

<div class="col-6 col-xs-12  " style="text-align:-webkit-center;">  

 <div class="slideshow-container">

<div class="mySlides w3-container w3-center w3-animate-right">
 <h2 class="font-size" id="f37" data-animation="fadeInUp" data-delay="200ms">1</h2>

</div>

<div class="mySlides w3-container w3-center w3-animate-right">
 <h2 class="font-size" id="f37" data-animation="fadeInUp" data-delay="200ms">2</h2>

</div>

<div class="mySlides w3-container w3-center w3-animate-right">
 <h2 class="font-size" id="f37" data-animation="fadeInUp" data-delay="200ms">3</h2>

</div>

<a class="prev" onclick="plusSlides(-1)">&#10094;</a> 
<a class="next" onclick="plusSlides(1)">&#10095;</a>

   </div>
</div>

Here's the JS

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

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

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

  function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
              }
  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";
            }
</script>

I hope my question is clear. Any help would be greatly appreciated. I've added the code to codepen so you can see the strange behavior it exhibits when the arrows are clicked, despite the auto-slides working correctly when idle. https://codepen.io/mahirq8/pen/JjjJzbe

Thank you

Answer №1

To achieve that functionality, you can utilize the setTimeout method.

Start by declaring a variable named timer at the beginning of your script:

var timer;

Within your showSlides function, insert the following two lines (you can place them anywhere, even at the end):

clearTimeout(timer);
timer = setTimeout(() => plusSlides(1), 2000);

By implementing this approach, if you continue to use the arrow-buttons, the timer will reset and resume sliding the slides after a 2-second interval from your last involvement.

You may preview the functionality here:

(previews of JavaScript and CSS code)

Answer №2

Insert the following code inside the <script> tag.

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  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, 2000); // Transition to next image every 2 seconds
}

The crucial line missing is the last one: setTimeout(showSlides, 2000);

If you want to view the code directly, click on this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto

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

The 'OR' statement in jQuery (||) is not functioning correctly within an if condition

I am facing an issue with a dropdown menu and colorizing its options based on their values. Here is the scenario: If the Option value is "f1" OR "f2", then the dropdown color should be "blue". Otherwise, it should be "red". Below is the code snippet: &l ...

What are the implications of using a non-200 status code in my controllers to intentionally trigger an ajax error?

Below is an example of code I have for a remote form: def something @user = User.find_by_email(params[:email]) @success = true @error = nil if !@user @success = false @error = "No such user" elsif <a href="/cdn-cgi/l/email-protection" ...

Problem with stacking order in Internet Explorer 7

Our current issue involves a z-index problem with a div that should be positioned above another specific div. The div in question, named (house-over-banner), is set to absolute positioning, while the one below it is relative. Interestingly, everything dis ...

Is there a streamlined approach to signal a successful callback to $q.all without the need to define a $q.defer() variable?

Within my application, I have a mixture of synchronous and asynchronous methods. Here is an example of code from one of the controllers: $q.all([ asyncMethod1(), syncMethod1() ]) .then(function (results) { Even though I don't actually need t ...

Incorporating a dropdown change event in HTML

Is there a way to implement a Dropdown onchange function in HTML to pass value without using a submit button? I have tried it with the submit button and it works fine, but I'd prefer to use the dropdown onchange event. Can someone please assist me on ...

Is there a way to programmatically access the title of a TitledPane in JavaFX without using CSS?

Is there a way to set the title of a TitledPane to bold in Java code without using CSS? I created a TitledPane and I want the title's font weight to be bold. This is what I tried: TitledPane Rootpane = new TitledPane(); Rootpane.setText("Options"); ...

The process of retrieving child data from a JSON object

I have a JSON object that I am attempting to iterate through, which is being returned via a Netsuite script. The JSON object contains some child elements. I am specifically trying to access the caption for data under "classnoheirachy - name", but I am un ...

How can I assign a default value to an angular 2+ dropdown menu? [I have not found a solution in previous inquiries]

When I attempt to set a default value with an empty channelId, it works as expected. Here is the example code snippet: destChannelList = [ { "channelId":"", "channelName":"SMS" }, { "channelId":1, "channelName":"Voice" ...

Can REST calls be initiated when the CSP is unable to be modified from the default-src: 'none'?

Sometimes, I wonder if this question is silly because it goes against the purpose of the Content Security Policy. There's a webpage located at foo.baz.com that requires data from bar.baz.com to function locally. Below is the code snippet for the func ...

Fill a small number of records

Consider this example Schema: const BookSchema = new Schema({ title: { type: String }, user: { type: Schema.ObjectId, ref: 'User' } }); If I have 10 records in the MongoDB book collection, and when quer ...

Achieving victory through res.send

Currently, I am utilizing a combination of Node and Angular JS, in addition to express-4. Within my code, the issue arises when I attempt to transmit newSourceId using res.send. Despite successfully retrieving the newSourceId, it consistently triggers an ...

Limiting the input in a text box to only allow whole numbers and no decimal values

What is the best way to limit a textbox to only accept whole numbers and exclude decimal values and alphabets? ...

Is there really a need to go through the hassle of creating a pure javascript/jquery widget when I can simply load it into an

Previously, I had a widget with the following code: <script src="http://www.mywebsite.com/widget/widget.js?type=normal" type="text/javascript"></script> <div id="archie-container"></div> This widget checked for the presence of jQu ...

Tips for utilizing the window object in Angular 7

To implement the scrollTo() function of the window object directly, we can use window.scrollTo(0,0). However, when researching how to do this in Angular, I found that many people create a provider as shown below: import {InjectionToken, FactoryProvider} f ...

Tips for restricting the options available in a select dropdown menu

Currently, I am in the middle of a project that involves using React and tailwind. In this project, I need to implement filtering options where only a maximum of 3 options are displayed. The challenge is that I want to filter based on specific letters ent ...

Challenge with timing in slideUp and slideDown animations (jQuery)

The element with the class "heady" is designed to slide up when the document height percentage is below 25%. If you scroll back up, it should reappear after a delay of 1400ms. The problem arises when this action needs to repeat, as the class does not sli ...

Text gradually appearing using a text button

I am currently trying to implement a fade-in effect on text in WordPress when another text line is clicked. I want the transition to be smooth and appealing, similar to a button. Despite my efforts, the method I found online does not seem to work correctl ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...

Linking information within a three-dimensional mesh structure in the context of a city created through procedural generation

Currently, I am working on developing a procedurally generated city using three.js, focusing mainly on creating buildings. One of the crucial requirements for this project is that when a user clicks on a building with their mouse, detailed information abou ...

Update array of hotel room reservations using Mongoose

I am currently developing a hotel room reservation system and have defined the attributes in the Room model as follows: rId: String, allocation: [{ date: Number, // 210403 == 2021-04-03 slots: [{ type: mongoo ...