Advertisement
AyanUpadhaya

Debouncing and Throttling example in JS

Aug 16th, 2023
891
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.63 KB | Source Code | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.   <head>
  4.     <meta charset="UTF-8" />
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6.     <title>UI Lab</title>
  7.   </head>
  8.   <body>
  9.     <h1>Debouncing and Throttling</h1>
  10.     <input type="text" onchange="debouncer()" />
  11.     <button id="btn" onclick="throttler()">Click</button>
  12.  
  13.     <script>
  14.       //debouncer
  15.       //debouncer is the mechanism that allows us to execute an
  16.       //operation after a certain amount of period
  17.       const getData = ()=>{
  18.             let counter = 0;
  19.             console.log('Fetched data ',counter++);
  20.         }
  21.       const myDebouncer = (call,loadTime)=>{
  22.           return function(){
  23.             let timer;
  24.             if(timer) clearTimeout(timer)
  25.             timer = setTimeout(()=>{
  26.                 call();
  27.             },loadTime)
  28.         };
  29.       }
  30.       //throttler
  31.       //throttling - action gets called after a period but
  32.       //we restrict user causing action until the previous action is over.
  33.       //or I should say how many time you can casue action in a certain period.
  34.       const getConnection =()=>{
  35.         console.log("Connected to server");
  36.       }
  37.       const myThrottle = (call,loadTime)=>{
  38.        
  39.         return function(){
  40.             document.getElementById('btn').disabled = true;
  41.             setTimeout(()=>{
  42.                 call()
  43.                 document.getElementById('btn').disabled = false;
  44.             },loadTime);
  45.         };
  46.       }
  47.  
  48.      
  49.       const debouncer =myDebouncer(getData,3000);
  50.       const throttler = myThrottle(getConnection,5000);
  51.     </script>
  52.   </body>
  53. </html>
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement