"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section.

<div class="rotating_block">
    <div class="block one"></div>
    <div class="block two"></div>
    <div class="block three"></div>
</div>
<br>
<div class="rotating_block">
    <div class="block one"></div>
    <div class="block two"></div>
    <div class="block three"></div>
</div>

Below is the CSS for the carousel:

.rotating_block {
  display: flex;
}
.one {
  background: red;
  height: 100px;
  width: 100px;
}

.two {
  background: green;
  height: 100px;
  width: 100px;
}

.three {
  background: blue;
  height: 100px;
  width: 100px;
}

In my JavaScript code, I have set up arrays like slideIndex and childrens to handle each carousel block separately.

The issue arises when I try to create a carousel function using setTimeout, as it results in a max call exceeded stack/console error being logged multiple times per second. Here's a snippet of the problematic code:

var slideIndex = [];
  var childrens = [];
  $(".rotating_block").each(function (index) {
    slideIndex[index] = 0;
    childrens[index] = $(this).find(".block");
    function carousel(children, slideIndex) {
      console.log('hello world');
      for (let i = 0; i < children.length; i++) {
        $(children[i]).hide();
      }
      if (slideIndex > children.length) {
        slideIndex = 1;
      }
      $(children[slideIndex - 1]).show();
      setTimeout(carousel(children, slideIndex), 5000);
    }
    carousel(childrens[index], slideIndex[index]);
  });

You can check out the full code example on CodePen.

Answer №1

One issue is arising because the function carousel is being passed parameters, resulting in an immediate function call.

setTimeout(carousel(children, slideIndex), 5000);

To resolve this problem, utilize an arrow function within setTimeout like so:

setTimeout(() => carousel(children, slideIndex), 5000);

ANOTHER POINT TO CONSIDER

In addition, remember to increment the value of slideIndex:

var slideIndex = [];
var childrens = [];
$(".rotating_block").each(function (index) {
  slideIndex[index] = 0;
  childrens[index] = $(this).find(".block");
  function carousel(children, slideIndex) {
    console.log(slideIndex);
    for (let i = 0; i < children.length; i++) {
      $(children[i]).hide();
    }
    //////////////////////
    slideIndex++;
    //////////////////////
    if (slideIndex > children.length) {
      slideIndex = 1;
    }
    $(children[slideIndex - 1]).show();
    setTimeout(() => carousel(children, slideIndex), 5000);
  }
  carousel(childrens[index], slideIndex[index]);
});

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 full width on hover even when the element has a specified width setting

I am encountering an issue with my CSS. Although I have successfully centered everything, I am facing a problem with the hover effect in CSS. Whenever I apply the active class or hover over an li element, the background color expands to 100%. Additionally, ...

Implementing the jQueryUI checkboxradio feature across all checkboxes within an entire ASP web application

I have a collection of Checkboxes in my ASP Webform app. I want to implement the jQuery UI checkboxradio() for all checkboxes in my app. To achieve this, I have added the following code in my Site.Master file. However, it is not functioning properly, even ...

Is it possible to persist $_SESSION data when sending ajax requests using jQuery in PHP?

I've almost finished a project that I'm quite proud of, but I've hit a snag with my ajax requests not sending $_SESSION data to the URLs they are supposed to load. My goal is to automate file uploads to YouTube using Gdata. When I make an aj ...

Tips for preventing the occurrence of a final empty line in Deno's TextLineStream

I executed this snippet of code: import { TextLineStream } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7201061632425c4341445c42">[email protected]</a>/streams/mod.ts"; const cm ...

When you have a target element that is deeply nested, consider using a 50% height relative to

There is some confusion surrounding the issue below: <div class="container"> <div class="row"> <div class="group"> <a> <div class="col-lg-3 full-h"></div> </a> <a> < ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

The breakdown of an object literal in JavaScript

What is the reason that we cannot access the second item in the object literal the same way as the first? var foo = {a:"alpha",2:"beta"}; console.log(foo.a) -> printing 'alpha' correctly console.log(foo.2) -> Error: missing ) after argumen ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

dynamic rendering in React based on the value passed through props

I am attempting to render a component using react.lazy, where the path is a variable in my props. However, I am encountering an error with webpack. The parent component sends the props like this: <DynamicModal url = 'Impuesto/formulario&apo ...

As a Java developer, I am currently facing challenges with mastering jQuery

Hi everyone, I am completely new to jQuery and have just started using the auto complete feature. I would like to make it so that when I click on an item provided by the auto complete, the page automatically submits to another page. Here is the code I a ...

Assistance needed to identify CSS issue specifically in FireFox browser

Working on a new webpage and encountered an issue with the HTML markup: <!DOCTYPE html> <html lang="en> <head> <meta charset="utf-8"> <title>TileTabs</title> <link rel="stylesheet" href="css/style.css" t ...

Using Android to Load HTML Content from a Database and Display in a WebView

I am currently facing an issue with loading HTML content from my sqlite database into a webview successfully. The HTML renders beautifully, however, the local file included in the HTML is not being loaded. I have placed it in the assets folder under this s ...

Creating a fullscreen layout in HTML with specific minimum and maximum widths

Looking to create a layout where one item takes up 1/3 of the screen-width with a minimum width of 500px and a maximum width of 700px, while another item fills the rest of the screen. Ideally, setting a width of 66% should work, but issues arise when the h ...

There is a problem with my module where multiple files that require it are overriding its variables

Currently, I am working on developing a mongo connection pool factory that is capable of checking if a connection to mongo already exists. If a connection exists, it will return that connection. However, if there is no existing connection, it will create a ...

Struggling with the conundrum of aligning a constantly changing element amid the

I was optimistic about the code I wrote, hoping it would work out in the end. However, it seems that my expectations might not be met. Allow me to provide some context before I pose my question. The animation I have created involves an SVG element resembl ...

Tips for executing getJSON requests one after the other

My goal is to showcase a weather forecast for a specific date on my website. Here are excerpts from the code I've used on a trial page that isn't functioning correctly: <script> function displayWeather(date){ $.getJSON(url + apiKey + "/" ...

Encountered an error when trying to access the 'modules' property of undefined in the /node_modules/bindings/bindings.js file while working with electron and setting up

1. npm install -g node-gyp 2. npm install serialport -S 3. npm install electron-rebuild -D 4. ./node_modules/.bin/electron-rebuild.cmd and after that, the rebuild process is completed. When I execute the command: npm run electron:serve, I encounter an ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

Using JavaScript to parse JSON data containing additional curly braces

Looking at this JSON object: var dataObj = { data: '\n{ sizeMap:{\nxSizes: "REGULAR|SMALL", \ncurrItemId: "",\ncurrItemSize: "",\nmanufacturerName:"Rapid",\npartNumber: "726G", \nsuitStyle: "R",\nhasSC: "",&bso ...

Discovering the key to selecting a row by double-clicking in Vuetify's v-data-table

I'm having trouble retrieving the row by event in my v-data-table. It only gives me the event and remains undefeated. How can I catch items in the v-data-table? <v-data-table :headers="showHeaders" :page="page&quo ...