JavaScript:防抖与节流
①防抖:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> div { height: 2200px; background-color: pink; } </style> </head> <body> <div>我是内容部分</div> <script type="text/javascript"> //防抖:函数只执行最后一次,若时间间隔小于500毫秒,则函数不执行 window.onscroll = debounce(function () { console.log("调用了1次"); }, 500) function debounce(func, delay = 300) { var timer return function () { var that=this var args=arguments clearTimeout(timer) timer = setTimeout(function(){ func.apply(that,args) //改变定时器中的this指向 },delay) } } </script> </body> </html>
②节流:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button>点击</button> <script> //节流:函数在一定的时间里只能执行那么几次,点击后等500毫秒触发,只能500毫秒触发一次 var btn = document.getElementsByTagName('button')[0] btn.onclick = throttle(function () { console.log(111); }, 500) function throttle(func, wait) { var timer return function () { var that = this var args = arguments if (!timer) { timer = setTimeout(function () { timer = null func.apply(that, args) //改变定时器中的this指向 }, wait) } } } </script> </body> </html>