節流
一定時間內只執行一次相關代碼
適用場景:
圖片懶加載 監聽滾動條
如滑鼠移動事件中onmousemove、滾動條事件等 ,如若事件觸發執行的相關代碼中有關于DOM節點的相關操作 又或者 ajax 請求介面,會造成計算機的性能的浪費,這種現象是我們不希望見到的
特點:監聽timer這個變數,如果timer為null的時候 才會執行callback
function throttle(callback, wait) {
var timer = null
return function () {
if (!timer) {
timer = setTimeout(function () {
foo()
timer = null
}, wait)
}
}
}
function foo() {
console.log(Math.ceil(Math.random() * 10))
}
window.addEventListener("mousemove", throttle(foo, 2000))
防抖
在一系列頻繁的操作下 只取最后一次(個人理解)
應用場景:
驗證碼六位數 在輸入最后一位后 自動提交表單
在調整螢屏大小時 有些瀏覽器 或者頁面可能會等到調整完成 才會執行callback 避免多次無意義的排版渲染
function throttle(callback, wait) {
var timer = null
return function () {
if (timer) {
clearInterval(timer)
}
timer = setTimeout(function () {
foo()
timer = null
}, wait)
}
}
function foo() {
console.log(Math.ceil(Math.random() * 10))
}
window.addEventListener("mousemove", throttle(foo, 2000))
總結:
防抖節流的核心都是setTimeout ,都是為了降低callback的執行頻率 節省計算機資源 優化性能 提高用戶體驗
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/185950.html
標籤:其他
上一篇:MySQL 之 進階操作
下一篇:道可道,非常道;名可名,非常名
