先做一個監聽鼠標移動的base:
<style>#content{height:150px;width:200px;text-align:center;color:#fff;background-color:#ccc;font-size: 70px;}
</style>
<div id="content"></div>
<script>let content = document.getElementById('content');let num = 0;function count () {content.innerHTML = num++};content.onmousemove = count;
</script>
// 鼠標在灰色方塊內移動時,數字會瘋狂的漲.
防抖(debounce): 是指觸發事件在n秒內函數只能執行一次,如果在n秒內又觸發了事件,則會重新計算函數執行時間
// 非立即執行: 本例中是指,鼠標移動,然后再某個地方停留s秒后,才執行函數
function debounce(func, wait) {let timeout;return function () {let self = this;let args = arguments;if (timeout ) clearTimeout(timeout);timeout = setTimeout( () => {func.apply(self, args);}, wait);}
}
content.onmousemove = debounce( count, 1*1000);// 立即執行: 立即執行,然后等待s秒(中途若移動則重新計算)后,然后立即執行,再等待s秒
function debounce(func, wait) {let timeout;return function () {let self = this;let args = arguments;if ( timeout ) clearTimeout( timeout ) ;let callNow = !timeout;timeout = setTimeout( () => {timeout = null;}, wait)if ( callNow ) func.apply(self, args);}
}// 混合防抖(immediate為真代表立即執行)
function debounce(func, wait, immediate=false) {let timeout;return function () {let self = this;let args = arguments;if( timeout ) clearTimeout( timeout );if( immediate) { // 立即執行let callNow = !timeout;timeout = setTimeout ( () => {timeout = null;}, wait)if ( callNow ) func.apply(self, args);} else {timeout = setTimeout( () => {fn.apply(self, args);}, wait);}}
}
節流(throttle): 所謂節流,就是指連續觸發事件,但是在n秒內該事件只處理一次
function throttle(func, wait) {let previous = 0;return function() {let now = Date.now();let self = this;let args = arguments;if (now - previous > wait) {func.apply(context, args);previous = now;}}
}
參考 函數防抖和節流