vue/js 优化代码

if (this.total > 3000) {
    setTimeout(() => {
       this.$refs.multipleTable.doLayout()
    }, 3000)
 }
if (this.total > 4000) {
    setTimeout(() => {
       this.$refs.multipleTable.doLayout()
    }, 4000)
 }
if (this.total > 5000) {
    setTimeout(() => {
      this.$refs.multipleTable.doLayout()
    }, 5000)
 }

上面这段代码重复性很高,请教大神们如何就写成一段!

在这里先感谢各位大神们的解答,小弟感激不尽!

阅读 3.5k
7 个回答

最大延迟 5000、同时是 1000 的整数倍呗?

if (this.total > 3000) {
    let ts = Math.min(parseInt(this.total / 1000) * 1000, 5000);
    setTimeout(() => this.$refs.multipleTable.doLayout(), ts);
}

setTimeout(() => this.$refs.multipleTable.doLayout(), Math.floor(this.total/1000))

function fn (time) {
    if (this.total > time) {
        setTimeout(() => {
               this.$refs.multipleTable.doLayout()
        }, time)
     }
}

根据你的提问,可以转换成这样。但是我觉得这样子可能会触发多次doLayout。
我觉得可以改成下面这样:

function fn () {
     setTimeout(() => {
               this.$refs.multipleTable.doLayout()
        }, Math.floor(this.total / 1000) * 1000)
}

只执行一次doLayout,根据total的值设置定时器的时间。

原来的代码其实存在重复设置setTimeout的问题,
按逻辑,延迟可能是3秒、4秒或者5秒建议改为

if (this.total > 3000) {
    let t=this.total-this.total%1000
    t=t<5000?t:5000
    setTimeout(() => {
       this.$refs.multipleTable.doLayout()
    }, t)
 }
const  list = []
if(xx){
 list.push(xx)
}
if(xxx){
 list.push(xxx)
}
list.forEach(res=> setTimeout(() => {
       this.$refs.multipleTable.doLayout()
    }, res))
setTimeout( () => {
    this.$refs.multipleTable.doLayout()
}, Math.floor(this.total / 1000) * 1000)
        let KEYPOINT = 3000;
        if (this.total > KEYPOINT) {
            let total = Math.floor((this.total - KEYPOINT) / 1000);
            for (let i = 0; i <= total; i++) {
                setTimeout(() => {
                    this.$refs.multipleTable.doLayout();
                }, i * 1000 + KEYPOINT);
            }
        }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题