I have a simple popup notification component that should hide after 4 seconds (opacity:0). Problem is that I want a notification to stay if I fire an event that makes a notification appear and then later disappear after 4 seconds. Now everything works as it should but setTimeout() stacks on each other, I want only last setTimeout() to fire, how do I achieve that?
So basically I want my notification to stay visible as long as a button that is emitting an event is being clicked and only last time that is clicked, setTimeout() should fire.
Here is my problematic code:
showNotification(v){
this.popupProduct = v;
this.showPopup = true;
setTimeout(()=>{
console.log(this.showPopup)
this.showPopup = false;
},4000)
},
Showing of notification is being dictated by this.showPopup
which is stored inside the Vue data object.
One way to do it is to store the id of the timeout and clear it at the beginning of the function:
showNotification(v) {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
this.timeoutId = undefined
}
this.popupProduct = v;
this.showPopup = true;
this.timeoutId = setTimeout(()=>{
console.log(this.showPopup)
this.showPopup = false;
},4000)
},