其实最先看设计模式是单纯的了解js语言自己;因此看了理解了以后仍是容易忘记;可能以后实际的工做须要才能记住吧;html
看下面:<!DOCTYPE html>ajax
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> </html> <script> window.onresize=function(){ con(); }; function con(){ console.log("aaaaa") } </script>
上述状况,浏览器大概每秒会检查到10次左右的窗口变化;显然对性能不利;设计模式
下面看一个节流函数作的处理:api
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> </html> <script>
window.onresize=function(){ throttle(con,300); }; function con(){ console.log("aaaaa") }
//节流器函数; function throttle() { var first_param = arguments[0], methods,time_param; if (typeof first_param === 'boolean') { methods = arguments[1]; methods.throttleTimeId && clearTimeout(methods.throttleTimeId); } else { methods = first_param; arguments.callee(true, methods); //arguments.callee指向函数的引用; //无闭包,当即销毁内存; time_param = arguments[1]||500//默认500毫秒; //函数的argument指向的是 实参; // window.throttle(true, methods); //arguments.callee指向函数的引用; //为函数绑定计时器,延迟执行 methods.throttleTimeId = setTimeout(function () { methods(); },time_param) } } </script>
经过把要执行的函数传入到节流函数中,达到效果;浏览器
当用户重复快速拖动窗口的时候,在设定的时间内 time_param;防抖函数检测有true时,立刻就清楚了函数的执行,除非用户在规定时间再也不操做;闭包
这个用在ajax重复提交按钮上面也是同样的;函数
简单假设:post
<input value="查询" id="btns">性能
$("#btns").on("click",function(){ui
throttle(query,300);
})
function query(){
$.ajax({
url:"api/user",
method:"post",
data:{
"name":"liuliu"
},
success:function(res){
console.log(res)
}
})
}