'How do I add a delay for hovering an element in angular?

I have an element:

<div (mouseenter)="enter()" (mouseleave)="leave()">Title</div>

TS:

onHover = false;

enter() {
    this.onHover = true;
    // doing some other stuff...
}

leave() {
    this.onHover = false;
    // doing some other stuff...
}

I want to add 2 seconds delay to mouseenter event like in this question. If user hovers >= 2 seconds on that element, I want to trigger mouseenter, not before. I tried setTimeout, but it doesn't work as intended.



Solution 1:[1]

I realised that I forgot to add clearTimeout. I've solved it like this:

onHover = false;
to;

enter() {
    this.to = setTimeout(() => {
        this.onHover = true;
        // doing some other stuff...
    }, 2000);
}

leave() {
    clearTimeout(this.to);
    this.onHover = false;
    // doing some other stuff...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YSFKBDY