Limit the frequency of function calls in Typescript

Update: After some research, I've learned that throttle has the capability to drop excess function invocations, making it unsuitable for my needs. I am still seeking an idiomatic solution to process every item in a queue at an appropriate pace without losing any items.


I'm currently developing a node application that interacts with an API having rate limits. The rate at which I can create calls surpasses the rate at which I can send them. I aim to consume a queue of calls while ensuring they are processed at the right speed and none are overlooked. To illustrate my issue, here is a small TypeScript test I have created:

import * as _ from "lodash";

let start = new Date().getTime();

function doLog(s: string) {
  let elapsed = new Date().getTime() - start;
  console.log(`${s} ${elapsed}`);
}

let array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
let throttled = _.throttle(doLog, 100);
array.forEach(s => throttled(s));

My expectation was to see output similar to:

a 2
b 101
c 203
d 302
e 405
f 502
g 603
h 706
i 804
j 902

However, what I actually observe is:

a 2
j 101

Here are some peculiar observations I've made:

  • With a throttle of 100ms, the size of the array doesn't seem to matter: only the first and last elements are printed, regardless of having 2 elements or 20.
  • Using a throttle of 1ms, I see the printing of 3-6 front elements from the array and the last element.

Answer №1

If you're not concerned about ensuring that doLog() is completed before calling the next one, simply utilize setTimeout

let items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
items.forEach((item, index) => setTimeout(doLog, index*100, item));

Adam provides a solid explanation for why using throttle may not be suitable in this scenario.

Answer №2

When a throttled function is invoked multiple times within its waiting period, the subsequent calls are simply disregarded. If your goal is to iterate through every element in an array, the throttle() method may not be the most suitable option. It is more effective for restricting excessive updates in the user interface, for instance.

The reason why you're consistently observing a and j in your output is due to the presence of both leading and trailing edges. Although the entire array was processed in under 100ms, with the defaults set to true for both leading and trailing, you witness both the initial and final invocations of the throttled function.

Answer №3

By incorporating RxJS, you can accomplish this task in a more idiomatic way with the help of the following solution:

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

Encountering an error of undefined upon submission of a form while utilizing ng

Sorry if this question has been asked before, but I've searched extensively online and still can't find a solution. I'm new to Angular and TypeScript and I may be overlooking something simple, but I can't get it to work. Any help would ...

To properly format the date value from the ngModel in Angular before sending it to the payload, I require the date to be in the format

When working with Angular 9, I am facing an issue where I need to format and send my date in a specific way within the payload. Currently, the code is sending the date in this format: otgStartDate: 2021-07-20T09:56:39.000Z, but I actually want it to be for ...

Link the chosen selection from a dropdown menu to a TypeScript object in Angular 2

I have a form that allows users to create Todo's. An ITodo object includes the following properties: export interface ITodo { id: number; title: string; priority: ITodoPriority; } export interface ITodoPriority { id: number; name ...

Adjusting the settimeout delay time during its execution

Is there a way to adjust the setTimeout delay time while it is already running? I tried using debounceTime() as an alternative, but I would like to modify the existing delay time instead of creating a new one. In the code snippet provided, the delay is se ...

Tips for setting up a React TypeScript project with custom folder paths, such as being able to access components with `@components/` included

I'm looking to streamline the relative url imports for my React TypeScript project. Instead of using something messy like ../../../contexts/AuthContext, I want to simplify it to just @contexts/AuthContexts. I attempted to update my tsconfig.json with ...

Fetching JSON data from a Node.js server and displaying it in an Angular 6 application

Here is the code snippet from my app.js: app.get('/post', (req,res) =>{ let data = [{ userId: 10, id: 98, title: 'laboriosam dolor voluptates', body: 'doloremque ex facilis sit sint culpa{ userId: 10' ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Encountered error E404 during installation of react packages using npm

Encountering an error while developing a Typescript-based fullstack project. The error message is as follows: npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@mui%2ficon-material - Not found npm ERR! 404 npm ERR! 404 '@mui ...

Error: Module not found '!raw-loader!@types/lodash/common/array.d.ts' or its type declarations are missing

I encountered a typescript error while building my NEXT JS application. The error message was: Type error: Cannot find module '!raw-loader!@types/lodash/common/array.d.ts' Below is the content of my tsConfig.json file: { "compilerOptions& ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

Angular 17 | Angular Material 17.3.1: Problem encountered with Angular Material form field focus and blur event handling

I attempted to apply (blur) and (focus) effects to my mat-form-field input field, but it seems like they are not working properly on my system. Here is a code snippet that resembles what I am using: html file <form class="example-form"> ...

Can you explain the distinction, if one exists, between a field value and a property within the context of TypeScript and Angular?

For this example, I am exploring two scenarios of a service that exposes an observable named test$. One case utilizes a getter to access the observable, while the other makes it available as a public field. Do these approaches have any practical distincti ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

The data type 'string' cannot be assigned to the data type 'undefined'

These are the different types available: export type ButtonProperties = { style?: 'normal' | 'flat' | 'primary'; negative?: boolean; size?: 'small' | 'big'; spinner?: boolean; } export type ...

Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to retu ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

Challenges faced while addressing angular package.json dependencies for a live build

For several hours now, I've been struggling to make npm run build:production work. This command is included as part of my build process when a branch is pushed. However, I have encountered an issue with my package.json file that I haven't been ab ...

Error: Unable to locate script.exe when spawning the Nodejs process

When trying to run an exe in my electron app, I am encountering an error. Even though the path is correct, it still throws an error. Uncaught Error: spawn exe/0c8c86d42f4a8d77842972cdde6eb634.exe ENOENT at Process.ChildProcess._handle.onexit (inter ...

Ensuring TypeORM constraint validations work seamlessly with MySQL and MariaDB

I recently started using TypeORM and I'm trying to incorporate the check decorator in my MySQL/MariaDB database. However, after doing some research on the documentation and online, it seems that the check decorator is not supported for MySQL. I'v ...