Can setTimeout be used to create a repeating animation loop?

Currently, I am in the process of creating a slider from scratch. Although there are ready-made plugins available for this purpose, my goal is to understand the underlying logic by building it myself. So far, I have managed to piece together most of the components, except for the part where I want the slider to loop back to the beginning once it reaches the last slide.

If you'd like to take a look at my progress so far, here is a link to a CodePen: https://codepen.io/alexyap/pen/zwoRMy

$(document).ready(function(){

function slide() {
setTimeout(function(){
  $("#container").addClass("slide-left1")
}, 3000);

setTimeout(function(){
  $("#container").addClass("slide-left2")
}, 9000);

}

slide();

My objective now is to create a loop within my sliding mechanism. I am considering utilizing the setTimeout functions to achieve this, allowing each slide to pause briefly both after page load and on specific slides. This will give visitors ample time to read any content present on each slide. Any assistance or guidance on how to accomplish this would be greatly appreciated. Thank you in advance!

Answer №1

Give this a try :

$(document).ready(function(){
  
  function slide() {
    setTimeout(function(){
      $("#container").removeClass("slide-left3");
      $("#container").addClass("slide-left1");
    }, 2000);

    setTimeout(function(){
      $("#container").removeClass("slide-left1");
      $("#container").addClass("slide-left2");
    }, 4000);
    
    setTimeout(function(){
     $("#container").removeClass("slide-left2");
     $("#container").addClass("slide-left3");
      slide();
   }, 6000);
  }
  
  slide();        
})
* {
  margin: 0;
  padding: 0;
}

body {
  width: 100vw;
  overflow-x: hidden;
}

#container {
  width: 300vw;
  background: #000;
  height: 100vh;
  position: relative;
  left: 0;
  transition: .9s ease;
}

#slide1 {
  background: red;
  height: 100vh;
  width: 100vw;
  left: 0;
  top: 0;
  position: absolute;
  transition: .9s ease;
}

#slide2 {
  background: yellow;
  height: 100vh;
  width: 100vw;
  position: absolute;
  left: 100vw;
  top: 0;
  transition: .9s ease;
}

#slide3 {
  background: blue;
  height: 100vh;
  width: 100vw;
  position: absolute;
  left: 200vw;
  top: 0;
  transition: .9s ease;
}

.slide-left1 {
  left: 0 !important;
}

.slide-left2 {
  left: -100% !important;
}

.slide-left3 {
  left: -200% !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div id="slide1">
  </div>

  <div id="slide2">
  </div>

  <div id="slide3">
  </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

What is the best way to display information in a Handlebars template file?

Having trouble displaying data in the template using NestJS with mysql. Here is the code snippet from controller.ts: import { Controller, Get, Post, Put, Delete, Body, Param, Render, UsePipes, Logger, UseGuards} from '@nestjs/common'; import { P ...

Extract the label from Chip component within the onClick() event in material-ui

-- Using Material-UI with React and Redux -- Within my material-ui table, there are <TableRow> elements each containing multiple <TableCell> components with <Chip> elements. These <Chip> components display text via their label prop ...

Steps to include a title next to a progress bar:

Is there a way to achieve something like this? https://i.sstatic.net/dhO2f.jpg I attempted to use bootstrap but I ran into an issue where the title was slightly misaligned below the progress bar. Can someone offer assistance with this matter? Apologies i ...

ReactJS: Error message indicating that the update depth limit has been exceeded

I'm facing an issue with toggling the state of a component in ReactJS. The error message I am receiving says: Maximum update depth exceeded. This can occur when a component repeatedly calls setState within componentWillUpdate or componentDidUpdate. ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

Customize MUI 5 input label background color for your own component

Struggling with overriding the background color for a MUI 5 input label on focus in a specific component? I successfully changed it to blue globally in my _theme.js file, but now need to make it red for my KeywordSearchTextField in index.js following MUI ...

Executing NodeJS commands and Linux commands via Crontab scheduling

I have an EC2 AWS instance where various commands and scripts work perfectly, but do not execute within a crontab. The Crontab contains: 15 03 * * * pythonscript1.py 45 03 * * * pythonscript2.py 00 05 * * * gsjson 1z5OlqsyU5N2ze1JYHJssfe1LpKNvsr4j8TDGnvyu ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

Is there a way to align an image alongside text in CSS with Bootstrap 4?

I am working on creating a box that displays the profile photo of a user along with their nickname on the right side. To achieve this, I have attempted various approaches while utilizing Bootstrap 4: My initial attempt involved using columns, but it did n ...

Verify if there is a cookie available; then execute the load() function. If the cookie matches, it is necessary to

$(document).ready(function() { var hrefs = { "en": ["includes/test1.html", "includes/test2.html"], "es": ["includes/test3.html", "includes/test4.html"] } $(function() { var cookie = Cookies.get('langCookie'); if (cookie) { ...

What is the process for creating a hover effect on a button that is triggered when a user hovers over the button's parent container?

Visit this link to view the code My Goal: I want the hover effect that normally applies to buttons when hovered over, to instead be applied when a user hovers over the parent div containing those buttons. The parent divs in question have a class of "ser ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

Issue with horizontal scrolling functionality in DataTables

I have a table with over 10 columns, and I am using datatables to display the data. I have enabled horizontal scrolling due to the large number of columns, but the scroll is not appearing. Can someone please assist me with this issue? Here is a screenshot ...

Run your node.js project on the internet

I have a node.js and socket.io project that I want to run on my server online. Using jade, I have organized everything in my local folder and successfully ran it locally. However, I now need to connect my phone to control my browser, which is not possible ...

Testing if the App properly renders results in an error message: "No element found with the text: Profil"

I am struggling with testing Jest as I lack experience in this area. Specifically, I need to determine whether the App component is being rendered successfully. However, my test cases are failing. Upon checking the console log, I encountered the following ...

Trigger an Ajax request upon user confirmation, which will only be prompted based on the result of a previous Ajax call

Currently, I am facing a challenging issue surrounding asynchronous calls: A specific JQuery function is triggered on user click. This function then requests a PHP file to check if the user input overlaps with existing information in the database. If an o ...

The headless mode of Google Chrome is displaying HTML content in a mobile-friendly format

I'm currently using Google Chrome headless with Laravel to convert HTML to PDF. However, I am facing an issue where it is rendering in a mobile view instead of displaying as a large screen-sized device. Here is my code: $content = '.......' ...

Troubleshooting the real-time replacement of LESS.CSS and CSS files using JavaScript

I'm facing an issue where I have a basic JS code that switches CSS files based on the size of the browser window. Here is the code: <script type="text/javascript"> //<![CDATA[ <!-- function adjustStyle(width) { width = parseInt(widt ...

Combining plugin setups and functionalities into a unified script

When it comes to grouping plugin initializations and scripts in a website, I often have a "tools.js" file that contains various functions, click events, and more. I prefer keeping all these script calls centralized in one file for simplicity, organization, ...