Beispiel – Wenn ich in weniger als 2 Sekunden (Verzögerung) abcd eingebe, sollte mein entprellter Wert sein abcd Stattdessen erhalte ich eine Konsole mit allen Werten-
Code: Select all
Debounced: a
Debounced: ab
Debounced: abc
Debounced: abcd
< strong>Code -
Code: Select all
import { useState } from 'react';
function debounce(cb, delay) {
let timeoutId;
return function (...args) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
cb(...args);
}, delay);
};
}
export default function App() {
const [searchVal, setSearchVal] = useState('');
const [debounceVal, setDebounceVal] = useState('');
const debouncedChange = debounce((inputValue) => {
console.log('Debounced:', inputValue);
setDebounceVal(inputValue);
}, 2000);
const handleChange = (e) => {
const inputValue = e.target.value;
setSearchVal(inputValue);
debouncedChange(inputValue);
};
return (
Debounce
{debounceVal}
);
}