This content originally appeared on DEV Community and was authored by Faisal Ahmed
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);
}
});
Explaination
- "h" টাইপ করলে কী হবে?
- শুরুতে throttleTimer ফাঁকা থাকে
let throttleTimer; // undefined
- if (!throttleTimer) চেক করবে → যেহেতু throttleTimer ফাঁকা, এটি true হবে
- শুরুতে throttleTimer ফাঁকা থাকে
if (!undefined) { // সত্য হবে, তাই ভেতরের কোড চলবে
- সার্চ লগ হবে
console.log("Searching for: h");
if (!undefined) { // সত্য হবে, তাই ভেতরের কোড চলবে
- throttleTimer সেট হয়ে যাবে, যাতে পরবর্তী ৫০০ms পর্যন্ত নতুন সার্চ না হয়
throttleTimer = setTimeout(() => {
throttleTimer = null; // ৫০০ms পরে null হয়ে যাবে, যাতে আবার সার্চ চালানো যায়
}, 500);
- "he" টাইপ করলে ১০০ms পরে কী হবে?
- এখন throttleTimer তে একটি টাইমার সেট আছে, তাই if (!throttleTimer) FALSE হয়ে যাবে
- ফলে console.log("Searching for: he") চলবে না!
Short explaination
- প্রথমবার if (!throttleTimer) true হয়, তাই ফাংশন চলে।
- এরপর ৫০০ms এর জন্য এটি false করে রাখা হয়, যাতে একই কোড বারবার না চলে।
- ৫০০ms পরে throttleTimer = null; সেট হয়, ফলে আবার if (!throttleTimer) true হয়ে যায়, এবং পরবর্তী ইনপুট লগ হয়।
This content originally appeared on DEV Community and was authored by Faisal Ahmed
Print
Share
Comment
Cite
Upload
Translate
Updates
There are no updates yet.
Click the Upload button above to add an update.

APA
MLA
Faisal Ahmed | Sciencx (2025-02-19T03:24:19+00:00) Throttling Technique in javascript. Retrieved from https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/
" » Throttling Technique in javascript." Faisal Ahmed | Sciencx - Wednesday February 19, 2025, https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/
HARVARDFaisal Ahmed | Sciencx Wednesday February 19, 2025 » Throttling Technique in javascript., viewed ,<https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/>
VANCOUVERFaisal Ahmed | Sciencx - » Throttling Technique in javascript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/
CHICAGO" » Throttling Technique in javascript." Faisal Ahmed | Sciencx - Accessed . https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/
IEEE" » Throttling Technique in javascript." Faisal Ahmed | Sciencx [Online]. Available: https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/. [Accessed: ]
rf:citation » Throttling Technique in javascript | Faisal Ahmed | Sciencx | https://www.scien.cx/2025/02/19/throttling-technique-in-javascript/ |
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.