js防抖,节流
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="text"> <div class="box"></div> </body> </html> <script> // 防抖(数据抖动):将多次操作变成一次 // 应用场景:input输入操作请求数据 let telInput = document.querySelector("input") telInput.addEventListener('input', dou(change, 2000)) //防抖函数封装 function dou(fn, time) { console.log('11'); let timeOut = null; return args => { if (timeOut) clearTimeout(timeOut) timeOut = setTimeout(fn, time) } } //改变触发 function change() { console.log('触发接口请求'); } // 节流:一定时间内只调用一次(下边的例子就是调用一次后2s内不再调用) // 应用场景:表单提交、高频监听事件 let box = document.querySelector('.box') box.addEventListener("touchmove", jie(change, 2000)) // 节流封装 function jie(fn, time) { let timeOut = null; if (!timeOut) { timeOut = setTimeout(() => { fn() timeOut = null }, time) } } </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div { height: 150px; line-height: 150px; text-align: center; color: #fff; background-color: #ccc; font-size: 80px; } h2 { margin: 10px 0; } p { color: #666; margin: 0; } </style> </head> <body> <p>说明:鼠标在以下元素不断移动,将会不断执行一个数值累加事件,但中间分别加入了防抖和节流函数。</p> <h2>防抖</h2> <p>在鼠标停止移动后300ms执行一次数值累加事件。</p> <div id="content">0</div> <h2>节流</h2> <p>在鼠标移动过程中,每300ms执行一次数值累加事件。</p> <div id="content2">0</div> </body> </html> <script> // 防抖函数 function debounce(func, wait) { let timeout = null; return function () { let context = this; let args = arguments; if (timeout) clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args) }, wait); } } // test debounce let num = 1; let content = document.getElementById('content'); function count() { content.innerHTML = num++; }; content.onmousemove = debounce(count, 300); // 节流函数 function throttle(func, wait) { let timeout = null; return function () { let context = this; let args = arguments; if (!timeout) { timeout = setTimeout(() => { timeout = null; func.apply(context, args) }, wait) } } } // test throttle let num2 = 1; let content2 = document.getElementById('content2'); function count2() { content2.innerHTML = num2++; }; content2.onmousemove = throttle(count2, 300); </script>