Angular mouseenter event delay not functioning after initial trigger

Currently, I am attempting to create a delay for the mouseenter event when the user hovers over a div. The goal is for the video to start playing only after the user has hovered for at least 1 second.

Initially, everything works as expected, but after the first time, it seems like the observable is behaving strangely and not emitting anything.

For instance, if I hover for less than 1 second on the first attempt and then return and hover for over a second, it does not trigger the event.

<div (mouseenter)="onMouseEnter($event)" (mouseleave)="onMouseLeave($event)"><div>

private _mouseEnterStream: EventEmitter<any> = new EventEmitter();
private _mouseLeaveStream: EventEmitter<any> = new EventEmitter();

  onMouseEnter($event) {
    this._mouseEnterStream.emit($event);
  }

  onMouseLeave($event) {
      this._mouseLeaveStream.emit($event);
  }

ngOnInit() {
    this._mouseEnterStream.pipe(flatMap((e) => {
      console.log(this._mouseLeaveStream)
      return of(e);
    }), delay(1000), takeUntil(this._mouseLeaveStream)).subscribe((e)=> { 
      console.log('mouseenter');
      this.loadVideo();
    });
    
    this._mouseLeaveStream.subscribe((e) => {
      console.log('mouseleave');
      this.pauseVideo();
    });
}

It is peculiar that if I include the following code snippet:

this._mouseEnterStream.pipe(flatMap((e) => {
      console.log(this._mouseLeaveStream)
      return of(e);
    }), delay(1000), takeUntil(this._mouseLeaveStream)).subscribe((e)=> { 
      console.log('mouseenter');
      this.loadVideo();
    });

within this section:

this._mouseLeaveStream.subscribe((e) => {
      console.log('mouseleave');
      this.pauseVideo();
    });

it works, but it doesn't seem like the correct approach.

Therefore, I need to figure out a way to ensure that this behavior is repeated for it to function correctly.

this._mouseEnterStream.pipe(flatMap((e) => {
      console.log(this._mouseLeaveStream)
      return of(e);
    }), delay(1000), takeUntil(this._mouseLeaveStream)).subscribe((e)=> { 
      console.log('mouseenter');
      this.loadVideo();
    });

Answer №1

To prevent any emits after the target observable emits, you should utilize takeUntil and create a new observable.

(Referenced from the example 3 in https://www.learnrxjs.io/learn-rxjs/operators/filtering/takeuntil)

mouseenter$.pipe(
  mergeMap(() => {
    // create a new observable
    return of({}).pipe(
      delay(1000),
      takeUntil(mouseleave$)
    )
  })
)
.subscribe(() => console.log('1 second has passed'));

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

Error: Trying to send FormData to ajax results in an Illegal Invocation TypeError being thrown

Successfully sending a file to the server for processing using the code below: var formData = new FormData(); formData.append('file', $('#fileUpload')[0].files[0]); options = JSON.stringify(options); // {"key": "value"} $.ajax({ ...

discord.js: Imported array not displaying expected values

I've been facing an issue with accessing elements from an imported array. Even though the array is successfully imported, attempting to access its elements using [0] results in undefined. Here's how I exported the array in standList.js: exports. ...

The XMLHttpRequest's readystate gets stuck at 1 stage

Feeling a bit out of practice here - used to work with AJAX directly, but then spent a few years on a jQuery site and now my native JS skills are rusty. I've simplified my code as much as possible, but it's still not functioning: var rawfile = ...

Modifying variable assignments in an Angular index.html file according to the environment

Is it possible to dynamically set the config.apiKey value in Angular based on different environments such as Development and Production? In a Production environment, use config.appKey = 'AB-AAB-AAB-MPR'; In a Development environment, use config ...

What is the best way to troubleshoot substrings for accurately reading URLs from an object?

While a user inputs a URL, I am attempting to iterate through an object to avoid throwing an error message until a substring does not match the beginning of any of the URLs in my defined object. Object: export const urlStrings: { [key: string]: string } = ...

Detecting changes in input text with Angular and Typescript

Searching for a straightforward and practical method to identify changes in my textfield has been challenging. Avoiding the use of (keypress) is necessary, as users may occasionally paste values into the field. The (onchange) event only triggers when the u ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...

Encountering error while running npm ci: 'Error reading property '@angular/animations' as undefined'

During the docker build process of my Angular project, I encountered an error while running the npm ci command: Cannot read property '@angular/animations' of undefined Despite the lack of a clear explanation in the error message, we have been st ...

Guide to iterating through a queue of promises (sequentially handling asynchronous messages)

Currently, I am working on processing a queue of promises (which are representations of messages) in a specific order and using AngularJS for the task. Just to give you an idea, let's say that I have a method called connect() which returns a promise ...

Utilize JavaScript to extract content from a text file and showcase it in a Bootstrap modal pop-up through knockout binding

I'm currently working on a function that reads data from a .txt file (located in the website's root directory) and then displays it in a modal dialog box. I believe I've made progress as the file is recognized during debugging, but unfortuna ...

Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet: <div v-for="item in my_items"> <div> <input type="text" :value=item.name /> </div> <div> <button @click="edit(item.id, item.name)">Edit ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

Repeated calls to Angular's <img [src]="getImg()"> frequently occur

Can someone help me figure out what's going on here? Recently, I set up a new Angular project and in app.component.html, I have the following code: <img [src]="getDemoImg()"> In app.component.ts: getDemoImg(){ console.log('why so m ...

JavaScript - undefined results when trying to map an array of objects

In the process of passing an object from a function containing an array named arrCombined, I encountered a challenge with converting strings into integers. The goal is to map and remove these strings from an object titled results so they can be converted i ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Creating a semi-circle donut chart with Highcharts using the Highcharts-ng library

I have been working on integrating a Highcharts Semi-circle donut chart into my angular application using the Highcharts-ng directive. However, I seem to be facing an issue where the plotOptions section is being skipped entirely, leading to a full circle p ...

A stateless component in React must always return a valid React element or null

I am a beginner with ReactJS and I am facing an issue. My goal is to showcase Hello world using the code snippet provided below, however, I keep encountering this error message: Can someone guide me on what I might be overlooking? The following is the c ...

Visual Studio Code unable to locate source maps for typescript debugging

Looking for some help debugging a basic Hello World TypeScript file. Whenever I try to set a breakpoint, it seems like VS Code is having trouble locating the source map, even though it's saved in the same directory. I'm using Chrome as my browser ...

"Enhancing the user experience: Triggering a window resize event in jQuery before page load on Magento

I am trying to trigger this function before the page finishes loading, but currently it only triggers after the page has loaded. Can anyone assist with this issue? $(window).on('load resize', function(){ var win = $(this); //this = window ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...