Move on to the following iteration within a (Typescript) .forEach loop by using setTimeout

Within my array, I have a list of image URLs that I need to update the src attribute of an img tag every 10 seconds. To achieve this, I am using a forEach loop which includes a setTimeout function that calls a DOM manipulation function (replaceImage) as shown:

const el = document.querySelector('img');
images.forEach((obj: Image, index: number) => {
    timer = window.setTimeout(() => {
        replaceImage(el, obj);
    }, index * 10000);
});

However, I encountered an issue where if a button is clicked, I want the loop to immediately move to the next iteration without waiting for the timeout to complete—essentially replacing the image right away.

I initially attempted to use the clearTimeout(timer) method upon button click to achieve this behavior.

It's worth noting that the above task is being carried out in a renderer process of an Electron application.

Answer №1

Store a list of image links you want to display (e.g. slideshow[url1, url2, ...]. Once the list is populated, a function can be called using

setTimeout(()=> nextImage(element, slideshow))
. The function nextImage(element, slideshow) can be implemented as follows:

const image = slideshow.shift();

if(image) {
    element.src = image;
    this.timer = setTimeout(()=>nextImage(element, slideshow), 10000);
}

This way, your images will be automatically replaced at regular intervals. Additionally, in your button click method, you can call element.src = slideshow.shift() and reset the timer if necessary by clearing and immediately setting it again.

Answer №2

It appears that this solution will meet your needs. Please be aware that the images will continuously cycle, meaning that after the last one, the first image will reload. Let me know if this behavior is acceptable for your requirements.

const el = document.querySelector('img');

let index = 0;
let interval;

const go = () => {
    const doImage = () => {
        replaceImage(el, img[index]);
        index = (index + 1) % images.length;
    };
    if (interval) {
        clearInterval(interval);
    }
    interval = setInterval(doImage, 10000);
    doImage();
}
go();

By clicking the button to call go(), the following actions will occur:

  1. The next image will be loaded immediately.
  2. The interval will reset, keeping the new image visible for 10 seconds before transitioning.

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

Using ES6 to Compare and Remove Duplicates in an Array of Objects in JavaScript

I am facing a challenge with two arrays: Array One [ { name: 'apple', color: 'red' }, { name: 'banana', color: 'yellow' }, { name: 'orange', color: 'orange' } ] Array Two [ { name: &apos ...

Attempting to iterate through an array of HTML5 videos

Having some trouble with my video array - it plays but doesn't loop. I've tried using the HTML video attribute 'loop' and variations like loop="true" and loop="loop" without success. Tonight, all I want is for it to loop properly! var ...

The 'innerText' property is not found in the 'Element' type

Currently, I am working with Typescript and Puppeteer. My goal is to extract the innerText from an element. const data = await page.$eval(selector, node => node.innerText); However, I encountered an error: The property 'innerText' is not ...

The issue with updating state in React using dispatch within the same method is not working

Initially, I had a situation where the state was updating correctly with two separate methods (onClick). const sizesMeasureChoise = useSelector(getSizesMeasureChoise); const chooseMeasure = (measure) => { dispatch(setSizeMeasureChoise(measure)); ...

Typescript enhances React Native's Pressable component with a pressed property

I'm currently diving into the world of typescript with React, and I've encountered an issue where I can't utilize the pressed prop from Pressable in a React Native app while using typescript. To work around this, I am leveraging styled comp ...

Unexpected behavior in resolving modules with Babel (using node and typescript)

Within my node project setup, I utilize babel-plugin-module-resolver for managing relative paths efficiently. tsconfig.json { "compilerOptions": { "outDir": "build", "target": "es5", ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

data not corresponding to interface

I am encountering an issue that says Type '({ name: string; href: string; icon: IconDefinition; } | { name: string; href: string; icon: IconDefinition; childs: { name: string; href: string; icon: IconDefinition; }[]; })[]' is missing the followin ...

What are some strategies for optimizing Next.js applications for mobile devices?

https://i.stack.imgur.com/mWmWG.png After realizing that the structure of my Next.js app doesn't align with Create React App's folder system, I'm stuck on how to effectively scale my website for mobile devices. In my confusion, I'm una ...

Node inadvertently triggers functions with similar names from a different module

Currently, I am developing a web application using Node and the Express framework. Within my project, I have organized two modules, CreateAccountService.js and LoginService.js, in the "service" directory. Each module currently only exports one function. ...

Navigating data within a JSON file with D3 javascript: a step-by-step guide

Currently, I am attempting to extract and manipulate data from a JSON file using D3 Javascript. Below is the content of the JSON file: { "Resources": [ { "subject": "Node 1", "group" : "1" }, { "predicate": ...

Applying the `lean` method to Mongoose queries that retrieve arrays in TypeScript

When working with two Mongoose queries, I made the decision to utilize the .lean() method on both of them. It appears that using .lean() on a query that returns a single document works well: let something:Something; SomethingDocument.findOne({_id:theId}) ...

Breaking down an Express app into modules: incorporating a function, a class, and req.pipe

Below are two servers and two gqlServers, each with different functionalities. All combinations of them work. The task at hand is to enhance express with predefined code patterns that can be shared across various apps through additional methods. What com ...

What are some solutions for resolving the npm error code elifecycle issue?

After following the documentation, I successfully installed React JS but encountered an error when trying to run the app. The error code displayed was elifecycle npm err errno 1. Can someone please assist me in resolving this issue? Additionally, it's ...

Warning: Unhandled promise rejection - Error encountered while trying to add response due to inability to set headers after they have already been sent to the client

After including the line res.status(201).json({ email });, I encountered an error message saying UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. How can I address this issue? Here is a ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

Display HTML containing a <script> tag within a REACT component

Looking to embed the following HTML code within a React component: <form action="/process-payment" method="POST"> <script src="https://www.example.com/payment-script.js" data-preference-id="$$id$$"> </script> </form> I ...

Customizing AngularJS Scripts to Include Target Blank

I'm feeling a bit lost. I need to include a target="_blank" on my anchor link. The issue is that the anchor tag is linked to a script in angular. I am not familiar with this JavaScript framework. I have tried searching through the documentation for po ...

Unable to locate Node.js /socket.io/socket.io.js on express 4.0

Currently, I am working on implementing a chat feature on my website. During testing on my local server, everything was running smoothly as port 8080 on localhost was readily available. However, after deploying my code to Heroku, I encountered an issue whe ...