参考:https://www.cnblogs.com/shuilangyizu/p/6816756.html
- 总是延迟1s(最好0.5秒左右)执行最后一次的resize。
var timer = null;
window.addEventListener('resize', function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
console.log("resize执行了");
}, 1000)
})
注:只有在拖拽窗口完成后才会改变echarts的大小!如果过程比较慢,一直是没有变化的!
这是一个小缺点。
- 使用节流阀
参考了评论项目里面的写法。注意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.节流阀;节流杆;风门;风门杆