原则:
1、多使用内存、缓存或者其他方法
2、减少CPU计算量,减少网络加载耗时
(防抖,节流,图片懒加载)
//防抖(input输入返回值)
input.addEventListener('keyup', debounce(()=>{ console.log(input.value) }),600) function debounce(fn,delay=500){ let timer = null;return function(){ if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(this,arguments) timer = null }, delay); } }
//节流(拖拽情况下返回坐标信息) const div2 = document.getElementById('div2') let timer = null ; div2.addEventListener('drag', throttle((e)=>{ console.log(e) },200)) function throttle(fn, delay = 500){ let timer = null; return function(){ if (timer) { return } timer = setTimeout(() => { fn.apply(this, arguments) timer = null }, delay); } }