Advertisement
STANAANDREY

debounce & throttle

Apr 24th, 2022 (edited)
1,931
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <head>
  5.     <meta charset="UTF-8">
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8.     <title>Document</title>
  9. </head>
  10.  
  11. <body>
  12.     <input type="text"><br>
  13.     default: <span id="default"></span><br>
  14.     debounce: <span id="debounce"></span><br>
  15.     throttle: <span id="throttle"></span><br>
  16. </body>
  17. <script>
  18.     function debounce(callbackFn, time) {
  19.         let timeOutObj;
  20.  
  21.         return (...args) => {
  22.             clearTimeout(timeOutObj);
  23.             timeOutObj = setTimeout(() => {
  24.                 callbackFn(...args);
  25.             }, time);
  26.         }
  27.     }
  28.  
  29.     function throttle(callbackFn, time) {
  30.         let waiting = false;
  31.         let waitingArgs;
  32.         const timeOutFn = () => {
  33.             if (waitingArgs == null) {
  34.                 waiting = false;
  35.             } else {
  36.                 callbackFn(waitingArgs);
  37.                 waitingArgs = null;
  38.                 setTimeout(timeOutFn, time);
  39.             }
  40.         }
  41.  
  42.         return (...args) => {
  43.             if (waiting) {
  44.                 waitingArgs = args;
  45.                 return;
  46.             }
  47.             callbackFn(...args);
  48.             waiting = true;
  49.             setTimeout(timeOutFn, time);
  50.         }
  51.     }
  52.  
  53.     const input = document.querySelector('input');
  54.     const defElem = document.querySelector('#default');
  55.     const debElem = document.querySelector('#debounce');
  56.     const thrElem = document.querySelector('#throttle');
  57.  
  58.     input.focus();
  59.     const updateDeb = debounce(text => {
  60.         debElem.innerHTML = text;
  61.     }, 2000);
  62.     const updateThr = throttle(text => {
  63.         thrElem.innerHTML = text;
  64.     }, 750);//*/
  65.     input.addEventListener('input', e => {
  66.         defElem.innerHTML = e.target.value;
  67.         updateDeb(e.target.value);
  68.         updateThr(e.target.value);
  69.     })
  70.  
  71. </script>
  72.  
  73. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement