Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Debounce Function ใน JavaScript คืออะไร?

Debounce function จำกัดอัตราที่ฟังก์ชันสามารถ fire ได้ เช่น autocomplete text bar ที่ query server ถ้า query ทุก keystroke จะมี network และ memory impact มากเกินไป ควรจำกัดจำนวน calls ในเวลาที่กำหนด

เขียน debounce function เองที่รับ actual function เป็น argument และ execute แบบ rate limited (throttled)

ตัวอย่าง

const debounce = (cb, time) => {    let timeout;    return function() {       const wrapperFunc = () => cb.apply(this, arguments);       clearTimeout(timeout);       timeout = setTimeout(wrapperFunc, time);    } }

ฟังก์ชันนี้รับ 2 arguments: callback และ interval ที่ควรเรียก สมมติ call แรกไปที่ 1ms และ set time 250ms จนถึง 251ms จะไม่มี call ใหม่ไปที่ API ไม่ว่าจะเรียกฟังก์ชันนี้กี่ครั้ง แทนที่ function call ของคุณด้วย debounce นี้ได้