DEV Community

Faisal Ahmed
Faisal Ahmed

Posted on

Throttling Technique in javascript

let throttleTimer;
const searchBox = document.getElementById('search-box');

searchBox.addEventListener('input', function (event) {
  if (!throttleTimer) { // যদি আগের কল থেকে নির্দিষ্ট সময় (৫০০ms) না কেটে থাকে
    console.log("Searching for:", event.target.value);

    throttleTimer = setTimeout(() => {
      throttleTimer = null; // ৫০০ms পর আবার নতুন কল করার অনুমতি দেবে
    }, 500);
  }
});

Enter fullscreen mode Exit fullscreen mode

Explaination

  • "h" টাইপ করলে কী হবে?
    • শুরুতে throttleTimer ফাঁকা থাকে
let throttleTimer; // undefined
Enter fullscreen mode Exit fullscreen mode
  • if (!throttleTimer) চেক করবে → যেহেতু throttleTimer ফাঁকা, এটি true হবে
    • শুরুতে throttleTimer ফাঁকা থাকে
if (!undefined) { // সত্য হবে, তাই ভেতরের কোড চলবে
Enter fullscreen mode Exit fullscreen mode
  • সার্চ লগ হবে
console.log("Searching for: h");
Enter fullscreen mode Exit fullscreen mode
if (!undefined) { // সত্য হবে, তাই ভেতরের কোড চলবে
Enter fullscreen mode Exit fullscreen mode
  • throttleTimer সেট হয়ে যাবে, যাতে পরবর্তী ৫০০ms পর্যন্ত নতুন সার্চ না হয়
throttleTimer = setTimeout(() => {
    throttleTimer = null; // ৫০০ms পরে null হয়ে যাবে, যাতে আবার সার্চ চালানো যায়
}, 500);

Enter fullscreen mode Exit fullscreen mode
  • "he" টাইপ করলে ১০০ms পরে কী হবে?
    • এখন throttleTimer তে একটি টাইমার সেট আছে, তাই if (!throttleTimer) FALSE হয়ে যাবে
    • ফলে console.log("Searching for: he") চলবে না!

Short explaination

  • প্রথমবার if (!throttleTimer) true হয়, তাই ফাংশন চলে।
  • এরপর ৫০০ms এর জন্য এটি false করে রাখা হয়, যাতে একই কোড বারবার না চলে।
  • ৫০০ms পরে throttleTimer = null; সেট হয়, ফলে আবার if (!throttleTimer) true হয়ে যায়, এবং পরবর্তী ইনপুট লগ হয়।

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay