Displaying a series of images sequentially with a pause in between using JavaScript

My goal is to cycle through images every 2 seconds in a specific order. I have implemented two functions, cycle and random. However, the cycle function seems to rotate too quickly and gets stuck without repeating itself in the correct order. On the other hand, the random function works perfectly fine, displaying a random image every 2 seconds.

<script>
    var asgnimage = ["pic2.jpg","pic3.jpg", "pic1.jpg", "pic4.jpg"];
     function cycle(){
        for (i=0; i<asgnimage.length; i++){
            document.cb.src = asgnimage[i];
                    window.setTimeout("", 2000);
        }
        window.setTimeout ("cycle()",2000);
    }

    function rndm(){
        var randomIndex = Math.floor(Math.random(randomIndex) * 4)

            document.rm.src = asgnimage[randomIndex];

            setTimeout ("rndm()",2000);
        }

</script>

Answer №1

Instead of using a for/loop, you can achieve the desired functionality with just one setTimeout that repeatedly calls the function. By passing additional arguments to the setTimeout function, you can modify the behavior of the cycling process - in this case, I will be passing a new index value.

const images = ["https://dummyimage.com/100x100/000/fff.png", "https://dummyimage.com/100x100/aa4cc3/fff.png", "https://dummyimage.com/100x100/556476/fff.png", "https://dummyimage.com/100x100/563765/fff.png"];

// Start with index 0
function cycle(index = 0) {

  // Display current image
  document.querySelector('#cb').src = images[index];

  // Reset index to 0 if end of array is reached, otherwise increment it
  let nextIndex = index === images.length - 1 ? 0 : ++index;

  // Call `cycle` again with the new `index`
  setTimeout(cycle, 2000, nextIndex);
}

cycle();
<img id="cb" />

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 manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

Array neighbors

Struggling to identify the 1's in my code's array while considering the corners and edges. #include <stdio.h> /* define grid size */ #define SIZE 7 int grid[SIZE][SIZE]; /* function to find the number of occupied adjacent cells */ int nei ...

Angular model remains static when incorporated within the document.addEventListener() attribute

Can anyone help me figure out why my attempt to update the model name this.name on click inside document.getElementById('source-selection').addEventListener is not working? Surprisingly, a simple alert within that function does trigger successful ...

"Employing regular expressions to extract the name of the web browser

Experiencing issues with regular expressions in JavaScript. Attempting to extract the version number and browser name, such as "Firefox 22.0" or "MSIE 8.0". console.log(navigatorSaysWhat()) function navigatorSaysWhat() { var rexp = new RegExp(/(firefox ...

Requirements for generating random numbers in JavaScript. Can anyone help me understand how to implement this requirement effectively?

I've been experimenting with JavaScript to create a blackjack game, but I'm having trouble getting my code to work properly. My goal is for the getRandomCard() function to generate numbers between 1 and 13. Specifically, I want it to return 11 wh ...

jQuery - class remains unchanged on second click event

Operations: Upon clicking on an element with the class thumb_like or thumb_unlike, a like will be added or removed for the image using a POST request. The element with the class thumb_count will increase or decrease based on user actions. For example, lik ...

Explore the OData hyperlink within BreezeJS

I've been working on integrating the BreezeJS library with an SAP OData service. I have successfully managed to read entities, but I'm facing issues when trying to resolve linked objects. The EntityType I am dealing with is OrgObject. <Entity ...

Prevent Cordova from shrinking the view when focusing on an input

Currently working on developing an app using Cordova/Phonegap (v6.5.0). Platforms where I've installed the app: - IOS (issue identified) - Android (issue identified) - Browser (no issue found) I am facing a known problem without a suitabl ...

A guide on creating a Utility function that retrieves all elements in an array starting from the third element

I've been working on a tool to extract elements from an array starting after the first 2 elements. Although I attempted it this way, I keep getting undefined as the result. // ARRAYS var arr = ['one', 'two', 'three', &a ...

Utilizing Javascript / jQuery to eliminate specific CSS styles

I am facing an issue with the CSS code for a table positioned at the bottom of the screen. The current code includes a filter specifically for IE 8, but I need to make it compatible with IE 10 as well by removing the filter and adding a background color. ...

Guide to performing a subdomain ajax request using jQuery (minus iFrames)

site.com/api/index.php is where the ajax request needs to go. While it works perfectly from site.com/sub/, it sends the request to sub.site.com/api/index.php from sub.site.com, which obviously does not exist. Despite researching extensively on Google and S ...

retrieve all entries from a paginated grid

Currently, I am utilizing the datatable feature in bootstrap4 with a table that has pagination set to display 10 items per page. I have implemented a function to retrieve values from the table, however I am facing an issue where I am only able to retriev ...

Array of arrays implemented in JavaScript

I'm working with a JavaScript array that contains string arrays: array1, array2, array3. I need to break this array down and access the individual arrays. What is the best way to achieve this? ...

Step-by-step guide to swapping an element with a textarea element using javascript

My current project involves creating a user profile that includes a text box where users can describe themselves. I've already implemented a separate page for editing the profile, but now I want to add a feature where users can hover over their descri ...

Disable infinite scrolling when a checkbox is clicked

Currently, I have implemented infinite scrolling on a table and it is functioning properly. <tbody infinite-scroll-disabled="myModule.isScrollingDisabled()" infinite-scroll="myModule.nextPage()" infinate-scroll-immediate-check="false" infinite-scroll-d ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

When using Flask, adding type=module to the src tag in HTML causes JavaScript to cease functioning

The task I had anticipated to be the simplest component of my project has transformed into a monumental challenge. My initial objective was to extract data from a JSON file for display on my website. Prior to implementing the JSON file, I manually input so ...

ChartJS v2: Displaying scale value based on click coordinates for time scale

I am having an issue with a time-based line chart where I am trying to retrieve the values for each scale at the click coordinates. In my ChartJS options, I have defined an onClick function: onClick: function(event, elementsAtEvent) { console.log(eve ...

The logic behind combining elements from two arrays in JavaScript/TypeScript

Explanation of two different array formats const arr1 = [ { "elementName": "one" }, { "elementName": "two" } ] const arr2 = [ { "type": "RPT_PROPERTY_DEMOGRP", "values": [ { "label": "HH" }, { " ...

Click to save image using jQuery

I am trying to implement a feature where clicking on an image allows users to download it. I am using the download attribute for this purpose. <a href="http://mysite.ru/userfiles/certificate_2.png" class="download-certificate-link" data-title="certific ...