Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped.

Below is the snippet in question :

let item = { id: 1, name: 'chair' };

const asyncItem = timer(2000).pipe(() => of(item));

asyncItem.subscribe(data=>console.log(data))

I anticipated seeing item displayed in the console after a 2-second delay, but strangely it appears instantly. Where am I going wrong? Grateful for any insights. Thanks.

Answer №1

If you want to trigger an emission after a certain number of seconds, make sure to utilize the delay operators instead of using timer.

To achieve this, modify your code as follows:

const asyncProduct = of(product).delay(2000)

asyncProduct.subscribe(data => console.log(data))

UPDATE: You can also opt for the timer operator within a pipe, combined with another operator like shown below:

timer(2000).pipe(
switchMap(() => of(product))
).subscribe(data => console.log(data))

By following this approach, the value will be emitted after 2 seconds, helping you accomplish your desired outcome. This presents an alternative method compared to the initial example provided earlier.

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

The issue with collapsible elements not functioning properly in an Angular application involving CSS and JS

My implementation of collapsible in a plain HTML page looks like this: <!DOCTYPE html> <html> <head> <title></title> <style> button.accordion { background-color: #777; color: white; cursor: pointer; p ...

Long loading times observed for larger datasets in Angular4 Datatable

I am currently experiencing slow loading times for my datatable when trying to display the data. The script is being called within the component like so: ngAfterViewInit() { $.getScript('./assets/js/datatables/datatable-basic.js'); } T ...

Combining ReactJS event handling for onClick and onKeyDown into a single handler for TypeScript

To ensure accessibility compliance, I am incorporating onKeyPress handlers into my application. However, I am facing a challenge with interactive <div /> elements. Here are the event handlers I want to trigger on click: const handleViewInfoClick = ( ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

Is it considered bad form to utilize nearly identical for loops in two separate instances within Angular 6?

I am working on creating two lists for a roster. The first list will display the current members of this year, while the second list will show if individuals have been excused for this year. After analyzing my code, I realized that I am using two identic ...

Provide information to spyOn and return a specific value

I am attempting to mimic a call to a service that involves an HTTP call. My goal is to provide fabricated data in the mock and verify it during my test. This is how I have set up the scenario: beforeEach(() => { fixture = TestBed.createComponent(MhS ...

Navigating a Laravel application with Angular 7: A comprehensive guide

Setting up a local server with LAMP, I am incorporating Laravel for the backend and Angular 7 for the frontend. Included in my web.php file is: <?php /* |-------------------------------------------------------------------------- | Web Routes |------ ...

Internet Explorer is throwing unexpected routing errors in Angular 2

I have a spring-boot/angular 2 application that is working perfectly fine on Chrome, Safari, Opera, and Edge. However, when accessed through Internet Explorer, the app directly routes to the PageNotFound component. I have tried adding shims for IE in the i ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Passing an event between components in AngularDart

Two components, componentA and componentB, are siblings within the structure of componentMother. When componentA is clicked, an event is triggered and handled by event handlerA. How can this event be passed to componentB and handled by event handler B? W ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...

Creating a specialized TypeScript interface by extending a generic one

Create a customized interface using TypeScript that inherits from a generic interface by excluding the first parameter from all functions. Starting with the following generic interface: interface GenericRepository { insertOne<E>(entity: Type<E& ...

Typescript's confidential variables

Currently, I am delving into the world of Angular2 and familiarizing myself with working with classes in javascript for the first time. I'm curious about the significance of using the private parameter in the constructor, as opposed to simply writing ...

Angular 5 Pipe fails to run in certain scenarios

I am new to Angular and I have created a custom pipe called "arrayToString" as shown below: import { Pipe, PipeTransform } from '@angular/core'; import * as _ from 'lodash'; @Pipe({ name: 'arrayToString' }) export class Arra ...

Trouble displaying object in template using Angular's ngrx

Within my Typescript interface, I have declared the following structure: export interface FolderList { ADMIN: [Folder[], string, string]; SUPERADMIN: [Folder[], string, string]; USER: [Folder[], string, string]; } The 'Folder' interface is de ...

I am having trouble getting my angular library published successfully

I'm facing an issue while trying to publish my angular package. I keep encountering this error. https://i.stack.imgur.com/nhYMY.png Here is a screenshot of my package.json file https://i.stack.imgur.com/mWsin.png. ...

How to send an ngFor element to a pipe in Angular 2 as an argument?

When attempting to pass an ngFor item into a pipe as a parameter, I encountered an error: Error: Call to Node module failed with error: Error: Template parse errors: TypeError: Cannot read property 'toUpperCase' of undefined ("{{name}} ng-cont ...

I'm attempting to retrieve mlab data in the console using node.js, but unfortunately encountering an error

I came across this helpful YouTube tutorial:https://www.youtube.com/watch?v=PFP0oXNNveg&t=460s. I followed the steps outlined in the video and made necessary code adjustments based on current updates found through a Google search (to resolve errors enc ...

Handling JSON Data in JavaScript

In the script below, I have a json object that is being processed: $http({ url: '/mpdValidation/mpdValidate', method: "POST", data: { 'message' : mpdData } ).then(function(response) { console.log(response.data ...