【问题标题】:Prevent setTimeout() from firing every time when hiding notification防止每次隐藏通知时触发 setTimeout()
【发布时间】:2021-01-14 13:51:14
【问题描述】:

我有一个简单的弹出通知组件,应该在 4 秒后隐藏(不透明度:0)。问题是,如果我触发一个使通知出现然后在 4 秒后消失的事件,我希望保留通知。现在一切正常,但 setTimeout() 相互叠加,我只想触发最后一个 setTimeout(),我该如何实现?

所以基本上我希望我的通知保持可见,只要一个正在发出事件的按钮被点击并且只有最后一次被点击时,setTimeout() 应该触发。

这是我有问题的代码:

showNotification(v){
        this.popupProduct = v;
        this.showPopup = true;
        setTimeout(()=>{
            console.log(this.showPopup)  
        this.showPopup = false;

        },4000)
    },

通知的显示由存储在 Vue 数据对象中的this.showPopup 决定。

【问题讨论】:

    标签: javascript vue.js settimeout eventemitter


    【解决方案1】:

    一种方法是存储超时的id并在函数开始时清除它:

    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)
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      • 1970-01-01
      • 2019-12-27
      • 1970-01-01
      相关资源
      最近更新 更多