js中resize多次执行

参考:https://www.cnblogs.com/shuilangyizu/p/6816756.html

  1. 总是延迟1s(最好0.5秒左右)执行最后一次的resize。
var timer = null;
window.addEventListener('resize', function () {
    if (timer) {
        clearTimeout(timer);
    }
    timer = setTimeout(function () {
        console.log("resize执行了");
    }, 1000)
})

注:只有在拖拽窗口完成后才会改变echarts的大小!如果过程比较慢,一直是没有变化的!
这是一个小缺点。

  1. 使用节流阀

参考了评论项目里面的写法。注意this的问题!

window.addEventListener('resize',throttle(2000,change))


function throttle(delay,callback){
    var startTime=new Date().getTime();
    var timer=null;
    return function(){
        var currentTime=new Date().getTime();
        clearTimeout(timer)
        console.log("时间差:",currentTime - startTime);
        if(currentTime-startTime>2000){
            console.log("大于一秒...");
            callback();
            startTime=currentTime; // 注意:是startTime=curerntTime!
            // 不是currentTime=startTime
        }else{
            console.log("小于一秒...");
            timer=setTimeout(function(){
                callback();
            },2000)
        }
    }
}


function change(){
    console.log("resize执行了...")
    myChart.resize();
}

throttle
英 [ˈθrɒtl] 美 [ˈθrɑːtl]
v.使窒息;掐死;勒死
n.节流阀;节流杆;风门;风门杆

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值