前置知识
关于this指向问题,防抖函数中的fn.apply(this,arguments)作用
防抖函数中的fn.apply(this,arguments)作用
this指向问题
节流
- 一定时间内只执行一项任务
节流原理
- 执行一个函数
- 执行这个函数的时候看看前面有没有执行过
- 如果前面有执行过这个函数并且没有完成,那么本次任务就不执行
节流前
可以看到"move"疯狂输出
节流后
程序输出move的次数明显减少
节流函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
function throttleMy(fn, delay) { var timer=null; return function (...args) { if (timer) { return; } timer = setTimeout(function () { fn.apply(this, args); timer=null; }, delay); } }
|
节流函数使用示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| <!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></title> <style> .box { width: 100px; height: 100px; background-color: red; position: relative; top: 100px; } </style> </head> <body> <div class="box"> </div> <script> var box = document.querySelector(".box"); window.onmousemove=throttleMy(function(e){ box.style.left = e.pageX - (box.clientWidth) / 2 + "px"; box.style.top = e.pageY - (box.clientHeight) / 2 + "px"; },40)
function throttleMy(fn, delay) { var timer=null; return function (...args) { if (timer) { return; } timer = setTimeout(function () { fn.apply(this, args); timer=null; }, delay); } } </script> </body> </html>
|
防抖
防抖原理
- 执行一个函数
- 执行这个函数的时候一段时间后如果有东东再次执行这个函数,则重新计时后在次调用
防抖前
输入框输入"你好"
防抖后
输入框再次输入"你好"
可以看到少了很多次
防抖函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
function debounce(fn, delay) {
var timer = null; return function (...args) { if (timer) { clearTimeout(timer); } timer = setTimeout(function () { fn.apply(this, args); timer = null; }, delay); } }
|
防抖函数使用示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| <!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" id="useript"> <script> var ipt = document.getElementById("useript"); ipt.onkeyup=debounce(function(e){ console.log(e); },40);
function debounce(fn, delay) { var timer = null; return function (...args) { if (timer) { clearTimeout(timer); } timer = setTimeout(function () { fn.apply(this, args); timer = null; }, delay); } } </script> </body>
</html>
|
娱乐一刻
"昨晚你终于回我信息了,你回了一句谢谢还加了一个爱心。当时我在工地上激动的差点把隔壁的吊塔阿姨给亲了。不过我想了想你笑起来的样子我还是忍住了。你给我发爱心,一定是已经爱上我了吧,放心,我连咱们的孩子名字都想好了。XX等我,我一定会继续努力挣钱,给你买更多的化妆品,发更多的红包!!"