手写节流和防抖 Bertha 。 2022-12-10 01:17 161阅读 0赞 <body> <button id="btn">点击防抖</button> </body> <script> var btn = document.getElementById('btn') function click() { console.log(111); } function debounce(fn, delay) { return function () { let that = this; let args = [...arguments]; clearTimeout(fn.id); fn.id = setTimeout(function () { fn.call(that, args) }, delay) // 当然如果setTimeout使用箭头函数的话,就不用that去存储this了 //fn.id = setTimeout(() => fn.call(this, args), delay) } } btn.addEventListener('click', function () { debounce(click, 500)(); // debounce返回的是一个函数,因此要加个() 去执行这个函数 }) </script> <body> <button id="btn1">点击节流</button> </body> <script> function throttle(fn, delay) { let timer; return function () { let args = [...arguments]; if (!timer) { timer = setTimeout(() => { timer = null; fn.apply(this, args) }, delay) } } } function click() { console.log(222); } var btn1 = document.getElementById('btn1'); btn1.onclick = throttle(click, 1000) </script>
还没有评论,来说两句吧...