JSFiddle - React, Tailwind, and code Playground

by sg3s

JavaScript

// Give your code a unique namespace using an immediatly invoked annonymous function
    (function (window) {
        
        // For better management we could use some more variables
        // slider.images.length replaces maxvalue
        var slider = { 
            images: [
              "/images/image1.jpg",
              "/images/image2.jpg",
              "/images/image3.jpg"
            ], 
            current: 0, // name your variables semantically, we know this is going to have a value so don't 'append' things to the name that are obvious
            time: 5000
        };
        
        // separated the function so we DRY
        function rotate() {
            // Remember that the images array is 0 indexed and length gives the total amount of 
            // items in the array which will be one more, if they're the same then we reset 
            // current to 0
            if(slider.current == slider.images.length)
                slider.current = 0;
            
            // Code to do w/e
            console.log(slider.images[slider.current], slider.current);
            
            slider.current++;
            window.loop = setTimeout(rotate, slider.time);
        }
        
        // only thing about intervals really, they never stop, and can never be stopped
        // so better thing to do is use a recursive timeout, and ideally it should be available 
        // somehow so you can stop it outside of the script itself, in this case we put the 
        // reference on window.
        window.loop = setTimeout(rotate, slider.time);
    
    }( window ));