標籤:nbsp post ati method eof 執行 視窗 callee ble
其實最早看設計模式是單純的瞭解js語言本身;所以看了理解了之後還是容易忘記;可能之後實際的工作需要才能記住吧;
看下面:<!DOCTYPE html>
<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次左右的視窗變化;顯然對效能不利;
下面看一個節流函數做的處理:
<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重複提交按鈕上面也是一樣的;
簡單假設:
<input value="查詢" id="btns">
$("#btns").on("click",function(){
throttle(query,300);
})
function query(){
$.ajax({
url:"api/user",
method:"post",
data:{
"name":"liuliu"
},
success:function(res){
console.log(res)
}
})
}
JavaScript 函數節流