Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>UI Lab</title>
- </head>
- <body>
- <h1>Debouncing and Throttling</h1>
- <input type="text" onchange="debouncer()" />
- <button id="btn" onclick="throttler()">Click</button>
- <script>
- //debouncer
- //debouncer is the mechanism that allows us to execute an
- //operation after a certain amount of period
- const getData = ()=>{
- let counter = 0;
- console.log('Fetched data ',counter++);
- }
- const myDebouncer = (call,loadTime)=>{
- return function(){
- let timer;
- if(timer) clearTimeout(timer)
- timer = setTimeout(()=>{
- call();
- },loadTime)
- };
- }
- //throttler
- //throttling - action gets called after a period but
- //we restrict user causing action until the previous action is over.
- //or I should say how many time you can casue action in a certain period.
- const getConnection =()=>{
- console.log("Connected to server");
- }
- const myThrottle = (call,loadTime)=>{
- return function(){
- document.getElementById('btn').disabled = true;
- setTimeout(()=>{
- call()
- document.getElementById('btn').disabled = false;
- },loadTime);
- };
- }
- const debouncer =myDebouncer(getData,3000);
- const throttler = myThrottle(getConnection,5000);
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement