How can I halt further execution and update the user on their status using underscore's _.delay function?

Handling an array of input data with asynchronous calls for each element can be tricky, especially when trying to avoid hitting rate limits on a server. While underscore _.delay() can help with the processing, there are still a few challenges to address. How can we (a) cancel delayed execution if the user decides to stop, and (b) display status updates that include the current index of the array?

Here's the current code snippet...

function processArray(array) {
    var processElement = function(element) {
        return doAsyncTask(element);  // asynchronous task returning a promise
    };

    _.each(array, function(element, index) {
        _.delay(processElement, index * 1000, element);
    });
}

function userDecidesToCancel() {
    // need help here
}

In case a user cancels the process before element N, it's acceptable to let doAsyncTask(N-1) finish, but we shouldn't initiate work for any elements beyond that point (for N >= 1). Is there a way to achieve this?

When it comes to status updates, it's challenging to display progress elegantly. Ideally, we'd like to indicate when each item is completed out of the total, as shown in the following example...

    _.each(array, function(element, index) {
        _.delay(processElement, index * 1000, element).then(function(result) {
            // how to retrieve and log the result here for status update?
            console.log("Finished processing item " + index + " with result: " + result);
        });
    });

While part of the log message can be included in the processElement function (for logging the result), the index relative to the array length is crucial for displaying progress percentage. This index information should be handled within the _.each loop itself, rather than passing it to the processElement function.

Any assistance on these matters would be greatly appreciated. Thank you.

Answer №1

The _.delay function in Underscore simply acts as a wrapper for the original setTimeout function. By keeping track of all the timeouts created, you can easily cancel them using clearTimeout:

var cancellations = _.map(array, function(element, index) {
  return _.delay(processElement, index * 1000, element);
});

function cancel() {
  _.each(cancellations, function(cancellation) {
    clearTimeout(cancellation);
  });
}

One limitation of this approach is that it doesn't provide a way to retrieve the promise from processElement.

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

How can I eliminate the scrollbar from appearing on all browsers when visiting my website?

I've encountered an issue while building my portfolio with React.js. I'm having trouble removing the scrollbar. I've attempted using overflow: hidden for the parent element and overflow: scroll for the child div, but it's not producing ...

Information is inaccessible beyond onBeforeMount in the Composition API of Vue 3

In my code snippet block, I have the following code: <script setup lang="ts"> import ApiService from '../service/api' import { reactive, onBeforeMount } from 'vue' let pokemons = reactive([]) onBeforeMount(async ()=> ...

Route all Express JS paths to a static maintenance page

Need help with setting up a static Under construction page for an Angular Web App with Express Node JS Backend. I have a function called initStaticPages that initializes all routes and have added a new Page served via /maintenance. However, when trying to ...

Is there a way to dynamically update the polyline on the map when I drag a marker to change the path, removing the previous one in the process?

I'm still fairly new to working with Javascript and the Google Maps API. I've come across various solutions to a similar issue that I'm facing, but none of them seem to work for my specific code. I'm starting to question whether the pol ...

What is the best way to divide data prior to uploading it?

I am currently working on updating a function that sends data to a server, and I need to modify it so that it can upload the data in chunks. The original implementation of the function is as follows: private async updateDatasource(variableName: strin ...

Develop a basic encryption program using PHP that involves substituting characters

Looking to create a simple encryption function in PHP as a newcomer to the language. The idea is to transform a string by changing the characters, utilizing two arrays. The first array holds all characters in a sorted order: $true_chars = array('a& ...

Troubleshooting Issue with InfoWindow Display on Multiple Markers in Google Maps

I'm having trouble getting my markers to show different infowindows. No matter what I do, the markers always display the content of the last "contentString" in the loop. Despite reading through multiple posts on this issue, I haven't been able t ...

Utilizing numerous Nuxt vuetify textfield components as properties

Trying to create a dynamic form component that can utilize different v-models for requesting data. Component: <v-form> <v-container> <v-row> <v-col cols="12" md="4"> <v ...

Avoid making GET requests when clicking on a link

[UPDATE] I need help troubleshooting an issue with my ajax request. Here is the code snippet that I am working on: <a href="" class="undo_feedback">Undo</a> When I click on the link, it triggers an ajax POST request, but I encounter an error ...

How can I search multiple columns in Supabase using JavaScript for full text search functionality?

I've experimented with various symbols in an attempt to separate columns, such as ||, |, &&, and & with different spacing variations. For example .textSearch("username, title, description", "..."); .textSearch("username|title|description", "..."); U ...

Ensure execution post completion of evalAsync process

I am relatively new to working with JavaScript and Angular technology. I have encountered a situation where two separate pieces of code are running in different callbacks, triggered by third-party libraries (specifically Kendo UI library callbacks). One f ...

Filter out all elements that come before the comma in the sorted array's output

Looking for a solution to modify my code so the output is just "Bothell" without the comma and count part. let As = document.getElementsByTagName('a'); let towns = new Map(); for(let a of As) { let town = a.textContent.split(',') ...

Pressing a sequence of buttons to meet a requirement using JavaScript

Currently, I have a set of four buttons that trigger an alert message when all of them are clicked. However, I am looking to modify this behavior so that the alert is displayed only when specific combinations of buttons are pressed, such as button1 and b ...

Tips for storing an array of strings in a JSON file using Javascript

Is it possible to save an array of strings to a JSON file using Node.js? const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; example.json [ "a", "b&q ...

Creating a case-insensitive path for pages in NextJS can be achieved by ensuring that all

I have a file named about.tsx under the pages folder. This means that the path for accessing the page is /about, allowing me to visit it through example.com/about. Strangely, attempting to access the same page via example.com/About results in a 404 error ...

Unable to use jQuery to send a basic ajax request in order to retrieve a json file

Here is the code snippet: $(function() { $.ajax({ url:'http://localhost:3000/business_places', type:'GET', dataType:'jsonp', done: function(data){ alert(1) }, error: function(data) { ...

The command "npm run build" is failing and encountering errors within the webpack project

Today, when I ran npm run build in the terminal, my project stopped running and displayed 90 errors and 13 warnings. It was working fine yesterday, so I'm not sure what the issue could be. The only change I made was to a line of JavaScript code that i ...

Is there a way to reverse the hover effect on div elements?

Let's start by examining the code I've written: HTML: <div class="button_container"> <div class="inner_button"> <a href="#" class="button_text">Button</a> </div> <div class="button_side"> ...

Choosing an id of my preference to set as the value in the ng-options select list and ensuring proper binding with ng-model

When using Angular, I am trying to create a select list where the value corresponds to the actual id of an object. I want to bind this correctly with the ng-model directive. Here is my attempt: <select ng-model="selectedPersonId" ng-o ...

Can you provide the function that updates subscription and account details using Recurly JS?

Recurly has unfortunately declined to provide assistance with this issue. I must understand the specific format of the objects, as Recurly will not process any extra data or incorrect query arguments (which vary for each function). Ruby: subscription = ...