Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Throttle & Debounce</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style>#info{position:fixed;top:8px;left:8px;background:#fff;border:1px solid #ccc;padding:6px}</style> </head> <body> <div id="info">Scroll & type to see throttled/debounced updates</div> <input id="search" placeholder="Type to search..." style="position:fixed;top:50px;left:8px;"> <script> function throttle(fn, wait){ var last=0; return function(){ var now=Date.now(); if(now-last>=wait){ last=now; fn.apply(this, arguments); } }; } function debounce(fn, wait){ var t; return function(){ var ctx=this, args=arguments; clearTimeout(t); t=setTimeout(function(){ fn.apply(ctx,args); }, wait); }; } $(window).on("scroll", throttle(function(){ $("#info").text("scrollY=" + window.scrollY); }, 100)); $("#search").on("input", debounce(function(){ $("#info").text("Search: " + this.value); }, 300)); </script> </body> </html>
Output