1. 程式人生 > 其它 >lodash防抖和節流簡單使用

lodash防抖和節流簡單使用

<!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>
    <style>
      html 
{ height: auto; overflow: scroll; } body { display: flex; flex-direction: row; justify-content: space-between; padding-top: 4rem; } div { width: 48%; overflow: hidden; } </style> <script src
="./plugins/lodash4.17.21/lodash.min.js"></script> <script> // 一些頻繁觸發的事件,我們不想讓它頻繁執行,比如 keyup scroll resize mousemove // 防抖:動作執行停止後間隔一定的時間執行,應用場景: 搜尋框聯想 // 節流:不管執行的頻率有多高,需要間隔一定的時間執行一次,應用場景:向下滾動載入資料 // 防抖和節流的區別:防抖:不管動作多少次,只有最後一次執行;節流:一段時間內執行多次,但人為地降低了執行的頻率 let i_left
= 0; let i_right = 0; document.addEventListener("DOMContentLoaded", () => { document.getElementById("input-text-left").addEventListener("keyup", () => { i_left++; console.log("left第" + i_left + ""); }); document.getElementById("input-text-right").addEventListener( "keyup", _.debounce(function () { i_right++; console.log("right第" + i_right + ""); }, 800) ); leftBoxEl = document.getElementById("left-box"); rightBoxEl = document.getElementById("right-box"); document.addEventListener("scroll", () => { imgEl = document.createElement("img"); imgEl.src = "./images/1.jpg"; leftBoxEl.appendChild(imgEl); console.log("left共" + leftBoxEl.querySelectorAll("img").length); }); document.addEventListener( "scroll", _.throttle(() => { imgEl = document.createElement("img"); imgEl.src = "./images/1.jpg"; document.getElementById("right-box").appendChild(imgEl); console.log("right共" + rightBoxEl.querySelectorAll("img").length); }, 1000) ); }); </script> </head> <body> <div id="left-box"> <input type="text" id="input-text-left" /> <img src="./images/1.jpg" /> </div> <div id="right-box"> <input type="text" id="input-text-right" /> <img src="./images/1.jpg" /> </div> </body> </html>