Using Angular's setTimeout() function with an external lambda that includes a parameter

My goal is to tackle two issues at once: 1) using

setTimeout( #action#, timeMillis)
with #action# as a lambda 2) supplying the lambda with a parameter.

The common method of

setTimeout( ()=>{ #callback# }, timeMillis)
works flawlessly when extracting ()=>{ #callback# } to lambda (in this case, lambda has no parameters). However, if I attempt to pass a lambda with a parameter to setTimeout, the function malfunctions - the callback triggers immediately.

Below is the code snippet:

let lambda = (text: string): TimerHandler => {
    alert(text)
    return ""
}

 .  .  .  .

lambda('text1')                     // value passes to lambda (displays 'text1')         - OK  |  no delay - X
setTimeout(lambda, 3000);           // value does not pass to lambda (shows 'undefined')   - X   |  delay    - OK
setTimeout(lambda('text3'), 3000);  // value passes to lambda (displays 'text1')         - OK  |  no delay - X

Note: Per setTimeout documentation, the first parameter #action# is of type TimerHandler, which extends string. Therefore, I return an "empty_string" inside the lambda body.

Could the unexpected behavior be due to the empty string in the return statement? I am unsure what should be set there.

Answer №1

If you want to properly utilize the setTimeout function, follow this method:

const delayFunction = (message: string): TimerHandler => {
  console.log(message);
  return '';
}

setTimeout(delayFunction, 3000, "hello");

Expected output after waiting for 3 seconds:

"hello"

Remember to provide arguments to setTimeout after the delay parameter.

The correct syntax is as follows:

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)

Answer №2

When you call

setTimeout(lambda('text3'), 3000);
, the function is executed immediately and its return value is then scheduled with a timeout, causing it to fire right away.

To prevent this immediate execution, you can follow the advice given in @bjdose's answer by passing parameters or using the callback form

setTimeout(() => { this.lambda('text4') }, 3000);
.

For a working example, check out this Stackblitz link.

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

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

A guide on exporting an Excel file with Spring Boot and Angular 2

To fulfill the requirements of my project, I am tasked with exporting customer data into an Excel file. Utilizing a table structure using Hibernate build. Here is my controller code: @RequestMapping(value="exporttoexcel", method= RequestMethod.GET, prod ...

Tips for retrieving the present value of a piped/converted BehaviorSubject

How do I retrieve the current value of the observable generated by readValue() below without subscribing to it? var subject = new BehaviorSubject<Object>({}); observe(): Observable<Object> { return subject.pipe(map(mappingfunction)); } Do ...

What is the best way to provide JSON data instead of HTML in Angular?

Is it possible to output processed data as json instead of html? I want to process backend data and output it as json for a specific url. How can I prepare a component to do this? Currently, the app serves html pages where components process backend data ...

Encountering a problem with package-lock.json during project deployment

My project publishing attempts keep resulting in the same error showing up repeatedly in the logs: Any thoughts on how this issue can be resolved? 18 error Command failed: git -c core.longpaths=true add D:...\main\backend\package-lock. ...

Having trouble managing TypeScript in conjunction with React and Redux

As a newcomer to TypeScript, I find myself struggling to grasp the concepts and know where to start or stop. While there are abundant resources available online, I have not been able to effectively utilize them in my project. I am hopeful for some guidance ...

Encountering difficulties in transmitting ngModel across multiple layers

I'm encountering a problem when trying to pass ngModel through the second child component. It seems that as soon as I do that, it stops working. In order to pass the ngModel, I implemented this abstract class: export abstract class AbstractValueAcces ...

What is the best way to hide the button when a user is viewing their own profile in an Angular application?

Each user has their own profile on the platform. A unique feature allows users to send messages by clicking a button when viewing other profiles. However, an issue arises where this messaging button also appears on a user's own profile. Is there a way ...

Why is my Angular 2 app (TypeScript) not functioning properly?

My current project includes a component called EventListComponent import { Component } from 'angular2/core'; @Component ({ selector: 'el-events', templateUrl: 'app/events/event-list.component.html' }) export class E ...

Managing DOM elements within a Vue 3 template using Typescript

As I delve into the world of Vue 3 as a beginner, I encountered a challenge when it came to managing the DOM within Vue 3 templates. Let's take a look at the source code. MainContainer.vue <template> <div class="main-container" r ...

Utilizing Typescript, create a customized dropdown with react-bootstrap for a tailored user

I've been working on incorporating a custom toggle drop-down feature based on the example provided on the react-bootstrap page, using Typescript and react functional components. Below is the code snippet for my component: import React from &apos ...

Every time I attempt to use interpolation in Angular 11, the result ends up being displayed as plain text on

I'm a beginner in Angular and I recently attempted my first code following a tutorial. When running this code on a live server using port 5500, I encountered an issue with interpolation. <h1>{{title}}</h1> The result on the webpage displa ...

Encountering a type error with mongoose's pre-save method while using Express with TypeScript

Currently, my tech stack consists of Express.js in TypeScript with Mongoose. Here is the model I am working with: import mongoose, { Schema, Document, Model } from 'mongoose'; import crypto from 'crypto'; import validator from 'val ...

Angular 5 is rendering a div even if there is no content present

I am currently using Angular 5.2 Firestore When using *ngIf isContent else noContent, my goal is to only render an Observable if it contains data. However, I am facing an issue where the logic always renders isContent even when there is no data present. ...

Error message in Angular states that it is not possible to bind to 'formGroup' because it is not recognized as a property of 'form' within Angular

When trying to extract data from a form using formcontrol, everything seems to be working fine except for the [formcontrol] = "userForm" in the HTML. If I remove this part, the project runs smoothly. I have tried multiple tutorials but none of them seem ...

Construct a string by combining the elements of a multi-dimensional array of children, organized into grouped

My task involves manipulating a complex, deeply nested array of nodes to create a specific query string structure. The desired format for the query string is as follows: (FULL_NAME="x" AND NOT(AGE="30" OR AGE="40" AND (ADDRESS ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Disabling click events on a span tag in Angular 6: A step-by-step guide

Is there a way to disable the click event for deleting hours with the 'X' symbol based on a condition? Thank you in advance. <table navigatable class="<some_class>"> <tbody> <tr *ngFor="let item of ...

Transmitting an array through a query parameter from Angular 6 to PHP

Hey there! I'm currently in the process of setting up an Angular application to make a GET request to my PHP backend. The PHP code is set up to expect three parameters - two strings and an array of strings. For example, it would look something like th ...

How can I efficiently iterate through the array of index IDs and then iterate individually through the communes, categories, and locations?

Currently, I am developing a nodejs typescript API where I am retrieving an array of objects using a map loop. The data for "communes", "category", and "location" is fetched from another API function based on the issuerId. However, I am facing issues with ...