Executing a delay in Angular 2+ using setTimeout()

Just starting out with Angular 2 and trying to implement setTimeout() in my app.component.ts file. I've looked at various posts for guidance but haven't been successful so far.

Below is the snippet of code I've been attempting:

app.component.ts

handleError() {
    if (navigator.onLine) {
        console.log("connected");
        this.displayNetworkError = false;
    } else {
        console.log("Disconnected");
        this.displayNetworkError = true;
    }
};

checkInternetConnection() {
    setTimeout(this.handleError(), 2000);
};

If anyone could provide some working examples, I would greatly appreciate it!

Answer №1

In order to use the setTimeout function in JavaScript, it is necessary to provide both a function and a duration in milliseconds. A typical way to pass a function is like this: setTimeout(function() {}, 1000). However, TypeScript allows you to use lambda expressions, making it possible to do so like this: setTimeout(() => {}, 1000)

Answer №2

When you call the function catchError using this.catchError(), you are actually executing it.

Just a reminder: the first argument of setTimeout should be a function, so make sure to use this.catchError instead of this.catchError().

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

Crafting a nested path type in Typescript

Currently, I am working on developing a recursive type in TypeScript to iterate through every potential route path, even nested paths, from a provided route configuration. However, I have hit a roadblock with type constraints and inference. The routes are ...

Run TypeScript with module import and definition using ts-node

I am attempting to initialize a database using TypeScript. Here is my TypeScript code: import { User, UserRole } from '../entity/User'; import crypto from 'crypto'; import {dbManager, pwhash } from '..'; async function initu ...

Examples or links pertaining to the tabs bar in Ionic

Is there a specialized tutorial or example available for finding non-default tabs in Ionic 5? I'm looking for alternatives to the default tabs and would appreciate any help in the form of links, examples, or tutorials. Thanks in advance! https://i.ss ...

Error: The specified property 'Body' is not found within the type '{}'

Looking for some assistance here. I've created an http.get method like this: return this.http .get(url) .map((response: Response) => { response = response.json(); // console.log('The http get response', respon ...

When attempting to run npm install for @types/jquery, an error is returned stating "Invalid name: @types/jquery"

npm install @types/jquery npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-c ...

Obtain an array containing various directives in a specific sequence

I am looking to extract directives from the view or content in the exact sequence they were specified in the template. First Attempt [view plunker] @Directive({selector: 'dir-1'}) class Dir1 {} @Directive({selector: 'dir-2'}) class Di ...

retrieve the router information from a location other than the router-outlet

I have set up my layout as shown below. I would like to have my components (each being a separate route) displayed inside mat-card-content. The issue arises when I try to dynamically change mat-card-title, as it is not within the router-outlet and does not ...

Identifying and handling errors in the outer observable of an RXJS sequence to manage

Encountered a puzzling rxjs issue that has me stumped. Here's the scenario: I have two requests to handle: const obs1$ = this.http.get('route-1') const obs2$ = this.http.get('route-2') If obs1$ throws an error, I want to catch it ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...

Customizing URL addresses based on webpack build configuration

Is there a way to parametrize the URL based on the webpack build profile? I'm referring to the URL used for services to fetch data from an API. For instance, in my Angular2 app: excerpt from package.json: "scripts": { "build-prod": "rimr ...

Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English. I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods. Within my provider, I have the following code: Provider: import { HttpClient } from '@angular/common/h ...

Is it possible to intercept Angular core methods in order to implement some Aspect-Oriented Programming strategies?

Currently working on a project using Angular 12, I'm wondering if there's a way to intercept calls to core methods like createComponent() from ViewContainerRef in the @angular/core library. This would allow me to implement some aspect-oriented pr ...

How to target a single TypeScript file in a React project that does not use TypeScript for compilation

I created a ReactJS application using the following command: $ npx create-react-app react-app-vanilla This app includes the following files: /.gitignore /README.md /package.json /public/favicon.ico /public/index.html /public/logo192.png /public/logo512.pn ...

The modal popup will be triggered by various button clicks, each displaying slightly different data within the popup

As a newcomer to Angular 4, I have encountered an interesting challenge. Currently, my code consists of two separate components for two different modals triggered by two different button clicks (Add User and Edit User). However, I now face the requiremen ...

Tips for showing a nested array in Ionic 3

I am trying to showcase the array of array data. This is how my API has responded: { "product_id": "13", "is_master": "0", "sku": "Variable_product_15", "upc": "", "price": "40.00000", "pricing_calculator": "standard", "shipping": "0", "p ...

Utilize [markdown links](https://www.markdownguide.org/basic-syntax/#

I have a lengthy text saved in a string and I am looking to swap out certain words in the text with a highlighted version or a markdown link that directs to a glossary page explaining those specific words. The words needing replacement are contained within ...

The TypeScript Type inside the Node Module Doesn't Seem to Be Functioning

In my React project, I am using the material-ui@next library along with typescript. Below is the code snippet that I have written: <CardMedia image={item.image_url} style={{ width: 238, height: 124.5 }} /> However, when I try to compile this code, ...

Validation Limit upto 30 days (Angular version 4 and above)

I am currently facing an issue with validation limiting to one month. I would like the Date validation to be restricted to a maximum of one month. Below is my validation function: public minmonthValidator() { let value = true; let endDate = t ...

Typescript error: The 'new' expression is missing a construct signature for its target, resulting in an implicit 'any' type

Here is a code snippet optimized for displaying custom errors in Chrome Devtools, Node.js, and other platforms. The inspiration for this came from this specific answer on StackOverflow. function CustomErr (message) { var err = new Error(message) Objec ...

Challenge with enforcing strong typing in Typescript

Here is the code snippet that I am working with: export type FooParams = { foo1: { x: number }; foo2: { y: string }; }; export type FooKey = keyof FooParams; // or export type FooKey = "foo1" | "foo2"; export interface FooAction&l ...