Function on NextJS site failing to adhere to the two-second timeout limit

I have implemented an 'image slide show' that switches between images every two seconds by toggling their display types from "none" to "block".

Within my .js file, the showSlides function is declared at the top:

var slideIndex = 0;

function showSlides() {
    if (process.browser) {
        let i;
        let slides = document.getElementsByClassName("introSlides");

        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";  
        }
        
        if (slideIndex >= slides.length) {
            slideIndex = 0
        }    

        //console.log("Displaying image %s/%s" % (slideIndex, slides.length))

        if (slides != null && slides[slideIndex] != null) {
            slides[slideIndex].style.display = "block";
            slideIndex++;
        }

        setTimeout(showSlides, 2000); // Change image every 2 seconds
    }
  }

Next, I have included four items and invoked the showSlides function within the HTML of the Home() function in the same .js file:

                {/*Character intros image gallery*/}
                <div class="fontSizeZero">
                    <div className="introSlides fade">
                        <img src="/poster-shinji.jpg" className="fullWidthImage"></img>
                    </div>

                    <div className="introSlides fade">
                        <img src="/poster-omi.jpg" className="fullWidthImage"></img>
                    </div>

                    <div className="introSlides fade">
                        <img src="/poster-crash.jpg" className="fullWidthImage"></img>
                    </div>

                    <div className="introSlides fade">
                        <img src="/poster-stiletto.jpg" className="fullWidthImage"></img>
                    </div>
                </div>

                {/*Call the slide show function*/}
                <script>
                    {showSlides()}
                </script>

However, this implementation only functions intermittently. Sometimes, the transition between images is too fast, making it hard to perceive the images. This issue seems to occur when leaving and returning to the page.

I am uncertain about the global slideIndex variable and would appreciate any suggestions on how to approach this implementation.

Apologies, as I am new to NextJS. Thank you for any advice.

Answer №1

There appeared to be various occurrences of the Timer, leading to disruptions in the DOM.

Changing the definition at the top of the .js file to incorporate Effects seems to have yielded positive results:

var slideIndex = 0;

const showSlides = setTimerId => () => {
    if (process.browser) {
        let i;
        let slides = document.getElementsByClassName("introSlides");

        for (i = 0; i < slides.length; i++) {
            slides[i].style.display = "none";  
        }
        
        if (slideIndex >= slides.length) {
            slideIndex = 0
        }    

        //console.log("Displaying image %s/%s" % (slideIndex, slides.length))

        if (slides != null && slides[slideIndex] != null) {
            slides[slideIndex].style.display = "block";
            slideIndex++;
        }

        setTimerId(setTimeout(showSlides(setTimerId), 2000));
    }
}

Within the Home function, we have integrated the Effect in this manner:

export default function Home() {

    const [timerId, setTimerId] = useState();
    const timerIdRef = useRef();

    timerIdRef.current = timerId;

    useEffect(() => {
        setTimerId(setTimeout(showSlides(setTimerId), 1000));
        return () => {
            clearTimeout(timerIdRef.current);
        };
    }, []);

The call to showSlides() has also been eliminated from the JSX within the Home function.

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 reason for the component that is imported conditionally not being displayed/render

I'm in the process of setting up a basic blog platform. My goal is to dynamically load a specific component based on the URL parameters (specifically, the id parameter). However, after implementing this code, the component always displays "Loading" ...

Is there a way to retrieve the Telerik HtmlAttributes values through javascript?

How can I retrieve HtmlAttributes values from a Telerik DropDownList? While I am familiar with using jQuery for this task, I would like to know the correct method for querying these values. @(Html.Telerik().DropDownListFor(model => model.BookingOff ...

You can click on the link within the Leaflet Popup to trigger JavaScript functionality

My leaflet map is functioning with GeoJSON polygons and popups attached to each one. These popups display information about the polygon. I want a link inside the popup that, when clicked, triggers a JavaScript function to retrieve and display smaller polyg ...

What is the best way to create a time delay between two consecutive desktop screenshot captures?

screenshot-desktop is a unique npm API that captures desktop screenshots and saves them upon request. However, I encounter the need to call the function three times with a 5-second delay between each call. Since this API works on promises, the calls are e ...

"A currency must be designated if there is a value present in a monetary field" - The default currency is established

I've encountered a major issue with one of my managed solutions. I have a customized workflow that generates multiple custom entities, each with various money fields. Here's the scenario when I trigger my workflow: The custom workflow enters a ...

Merging two arrays that have identical structures

I am working on a new feature that involves extracting blacklist terms from a JSON file using a service. @Injectable() export class BlacklistService { private readonly BLACKLIST_FOLDER = './assets/data/web-blacklist'; private readonly blackl ...

Error: Attempted to call $scope.map.control.getGMap function when clicking on the Map, but it is not defined

I'm currently working with Angular-Google-MAP and I'm trying to add a marker to the map. However, whenever I click on the map, I receive an error message saying $scope.map.control.getGMap is not a function. This error is occurring within the geoc ...

Ways to present a pop-up dialog box featuring word corrections

I have developed a word correction extension that encloses the incorrect word in a span element. Upon hovering over the word, a drop-down menu with possible corrections should be displayed. However, my current code is not functioning properly. How can I en ...

How to Utilize Class Members in a Callback Function in Angular 12 with Capacitor Version 3

When I click the "Device Hardware Back Button" using Capacitor 3.0, I'm trying to navigate to the parent component with the code below. The device back button is working correctly, but I'm facing an issue where I can't access class members i ...

What is the best way to eliminate wrapper spans from next/image in Next.js?

I'm currently learning Next.js and I've noticed that when using next/image, it wraps the img tag with additional spans and applies inline styles that override my custom class styles. Is there a way to remove the inline styles as well as the wrap ...

Troubleshooting Next.js deployment with Nginx: experiencing a 403 forbidden error with chunk script files

After deploying my Next app using Nginx, I encountered an issue where the js files inside the _next/static/chunks directory were getting a 403 forbidden error. https://i.stack.imgur.com/TB9TX.png Interestingly, only the js files in the chunks directory w ...

Encountering an error in React: Unable to access property 'elements' of undefined due to incorrect passing of the event object

Struggling to make a form submit text to send via axios to the backend API in React. Following an outdated tutorial and using antd library for the form template. Here is the current form code with some console logs to debug: import React, { useState } fr ...

Encountering a `404 Error - Page Not Found` issue while using Next.js version 14.1

I am having trouble navigating from the home page in the header section to the Login and Register pages. Whenever I click on either of them, I get an error immediately. The structure of my folders is as follows: src ...app ......layout folder Footer.jsx ...

Having difficulty importing app.js into other modules within ExpressJS

Having trouble importing app.js into other modules in ExpressJs. It imports successfully, but I can't use the functions defined in the app.js file. The code snippet I am working with is as follows: I have this app.js var app = express(); var express ...

Is the callback of $.post not being executed until the loop it's contained in finishes?

I'm working on a stock table that allows users to input the quantity of stock to issue. I have a function that verifies whether or not the database has sufficient stock for each entry in the table. When debugging through the code in Chrome, I noticed ...

How can we eliminate identical elements from an array in JavaScript and increment the count of other objects?

I currently have 1 object retrieved from local storage, but it seems to contain some duplicates. What is the easiest way to remove these duplicates? The array object I am working with is called "mainchart". function check() { for (let i = 0; i < main ...

Creating multiple objects in a threejs instance with varying sizes and positions

Recently, I decided to try out the InstancedBufferGeometry method in order to improve performance when rendering thousands of objects. Specifically, I wanted to create instances of cube geometries with varying heights. AFRAME.registerComponent('insta ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

What is the reason that preventDefault fails but return false succeeds in stopping the default behavior

I'm having trouble with my preventDefault code not working as expected. While using return false seems to work fine, I've heard that it's not the best practice. Any ideas why this might be happening? if ($('.signup').length == 0) ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...