Implementing Angular 4 setTimeout() function with dynamic delay and wait periods

My task involves managing a list of events that each have a specific timestamp. I am looking to display these events in the order of their timestamps.

To introduce a delay between events:

delay = timestamp(t+1) - timstamp(t)

I understand that implementing this with setTimeout may not be ideal, especially when the delay is not constant. However, there might be a workaround available for situations where the timeout remains constant, which is not the case for me.

Is it feasible to ensure that the next setTimeout() only triggers after the previous one has completed? For instance, if the first setTimeout() has a 5-second delay and the second one 3 seconds, the latter will execute before the former. My goal is to maintain the order specified by the timestamps while ensuring sequential execution.

The example provided illustrates how this can work with a fixed delay, but my scenario requires dynamically calculating the delay based on the event data obtained from iterating through the list.

for (i = 1; i <= 5; ++i) {
  setDelay(i);
}

function setDelay(i) {
  setTimeout(function(){
    console.log(i);
  }, 1000);
}

Answer №1

If you want to achieve a similar result, you can utilize an IIFE (Immediately Invoked Function Expression) combined with function recursion as shown below:

let counter = 0;
(function repeat(){
  if (++counter > 5) return;
  setTimeout(function(){
    console.log("Iteration: " + counter);
    repeat();
  }, 5000);
})();

Check out the live example on JSFiddle here.

Answer №2

It is not advisable to include this code snippet within a loop because the setTimeout function will not wait for completion.

An alternate approach would be to create a list of time intervals that you wish to wait for, and then iterate through them recursively:

let delays = [5000, 3000, 1000];

function delayExecution(times) {
  if (times.length > 0) {
    // Extract the first interval from the array
    let duration = times.shift();
    console.log("Waiting", duration);
    
    // Pause execution for the specified duration
    setTimeout(() => {
        console.log("Waited ", duration);
        // Execute the delayExecution function again with the remaining intervals
        delayExecution(times);
    }, duration);
  }
}

delayExecution(delays);

Answer №3

When utilizing the most recent Typescript or ES code, async/await becomes a great solution.

let timeIntervals = [3, 2, 4];

(async () => {
  for (let interval of timeIntervals) {
    await delay(interval * 1000);
    console.log('waited: ' + interval);
  }
})();

function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

In order to utilize await, we must encapsulate the for loop within an immediately invoked async function.

A timeout function is also necessary to return a promise upon completing the specified timeout duration.

Subsequently, we wait for the timeout to finish before proceeding with the loop iterations.

Answer №4

Adjust the time-out duration based on the dynamic value of i. Here's an example:

for (let i = 1; i <= 5; ++i) {
  customizeTimeout(i);
}

function customizeTimeout(i) {
  setTimeout(function(){
    console.log(i);
  }, i*1000);
}

Answer №5

Consider the following approach:

initializeDelay(1, 5);

function initializeDelay(counter, maximum) {
  setTimeout(function(){
    console.log(counter);
    if(counter < maximum){
      counter++;
      initializeDelay(counter, maximum);
    }
  }, 1000);
}

The concept here is to set the next setTimeout(.. within a timeout. Feel free to adjust it and change the duration of timeouts as needed.

Hopefully this explanation is helpful :)

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

Retrieving dates from a database and populating them into a jQuery UI Picker using PHP

I need to retrieve dates from the database using PHP and highlight them in a datepicker. Here is how I am attempting to accomplish this: HTML Date: <input type="text" id="datepicker"> // Static dates // An array of dates var eve ...

Exploring connections between various objects using JavaScript

Currently, I am working with two sets of arrays: $scope.selectedEmployees = ["1001", "1002"]; $scope.selectedTasks = ["Task1", "Task2"]; My goal is to create an array of objects that combine employees and tasks in a many-to-many relationship. The length ...

Vue.js HTML not refreshing after axios request changes object property

Issue with Vue.js not updating HTML after axios GET request. Here's the structure: <span @click="tryResponse"> Data_object: {{ data_object }} <br> Data_object.serial: {{ data_object.serial }} <br> </span> Data ...

How to programmatically open a new tab in Internet Explorer 7

I work on developing web applications using C#, ASP.NET 3.5, and Ajax 2.0. Query - While running Application_1 in Internet Explorer 7, I want to programmatically initiate the execution of Application_2 from Application_1 in a new tab, disregarding client ...

Encountering an error with type mismatch for style transform properties while using react-native-reanimated

Currently working with the following versions: "react-native": "0.59.10" "react-native-reanimated": "^1.3.0" using TypeScript Encountering a type error related to transform properties. const Example = () => { const { translationX, gestureHandler } = ...

What could be causing the need for RxJs TypeScript files to be requested exclusively when my website is hosted on IIS?

When I develop my site using Visual Studio / IIS Express, everything runs smoothly without any unusual requests or 404 errors. However, once I publish the site to IIS and try to run it, I start receiving multiple requests for typescript files (.ts), prima ...

Exploring the integration of Angular framework with Laravel

Currently, I am coding in Laravel 7 and Angular 10 separately. However, for my upcoming project, I will be incorporating both Laravel and Angular together. My plan is to integrate Angular into my Laravel application and leverage Angular for my JavaScript t ...

Attempting to initiate an AJAX request to an API

Hey everyone, I've been working on making an AJAX API call to Giphy but I keep receiving 'undefined' as a response. Can anyone offer some advice on how to troubleshoot and fix this issue? Thanks in advance for your help! var topics = ["Drak ...

Troubleshooting problem with nested object in AngularJS data table

For my project, I am utilizing an angular js datatable and currently trying to access the following object: "finalizedArr":[ { "treaceId":"KYC454353545", "approval":[ ...

Displaying text when hovering the mouse over an element

Currently, I am working on a task that involves making a background image disappear and then revealing some text with a link in the div. Although I have managed to make the image disappear upon mouseover, I am struggling to display the text. Below is my cu ...

Having trouble showing information in primeng treetable, and encountering issues with response data returning as undefined when logged in console

Model Definition This model defines the structure of the data export interface NewEvaluation { id?: number; criteriaId?:number; parameterType?:string; parameterName?:string; weight?:number; thisYear?:number; lastMonth?:number; thisMonth?:number; ...

Looking to Search For a String Using Regex in Javascript?

I am encountering a string that looks like this: "No reservation is available to allocate within the group StorageGroup1. Total 330 GB of storage was requested" However, sometimes I do not receive this exact string format, as the group name and total stor ...

Is there a way to determine if the browser window is currently in use?

The code I am currently working with looks like this: let focus; function setFocus() { focus = true; } function hideWindow() { focus = false; } window.onfocus = setFocus(); window.onblur = hideWindow(); The intention behind this code is to use it in the ...

Error: The server is unable to process the POST request to /api

Currently following a tutorial on YouTube: https://www.youtube.com/watch?v=4ECVE6TXKLQ&list=PLI-gk4ISRzCPlJjCz3yuAhL8vnmK6KWr7&index=11 After setting up a server listening on port 8080 and connecting to MongoDB Atlas successfully, the next step ...

Bring in a video file in order to watch it on your web page (HTML)

Is there a way to upload and play a video file using the video element? I am looking to add a video file to my webpage that can be played using a video element. <input type="file"> <h3>Video to be imported:</h3> <video width="320" ...

What are the steps to fix the configuration error caused by IIS?

I have successfully deployed my Angular application on IIS manager. After building the application with the command ng build --prod --base-href /home/, I added the data generated in the dist folder to the IIS application. Here are the files that were gen ...

ReactJs Error: Unable to access property value because it is undefined (trying to read '0')

I am currently attempting to retrieve and display the key-value pairs in payload from my JSON data. If the key exists in the array countTargetOptions, I want to show it in a component. However, I am encountering an error message stating Uncaught TypeError ...

Tips for implementing validation in template-driven form using Ionic 3

How can I validate a mobile number in an Ionic 3 application? I am using ngModel, but I'm looking for an example to help me with the validation process. Can anyone provide guidance on how to do this? <ion-list> <ion-item margin ...

Nuxt template failing to render properly

I'm new to Nuxt.js and I'm struggling to render the template on my localhost. Is there an issue with my code? <template> <div> <h1>Hello, World!</h1> </div> </template> <script> export default { ...

Angular: Simplifying nested array filtering

I'm trying to customize my sidebar menu by hiding certain paths based on the user's role. Here are some example routes: export const ROUTES: RouteInfo[] = [ { path: '/overview', title: 'Overview', type: 'li ...