I am trying to setup a debounce function which will handle an HTTP request function. The code is very similar to the following one, basically, I only changed the functions naming.
Firstly, I am using this debounce function.
function debounced(fn, delay) {
let timerId;
return function (...args) {
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn(...args);
timerId = null;
}, delay);
}}
And there is the example code which is a basic React'js class.
var Example = React.createClass({
getInitialState: function () {
return ({
counter: 0
});
},
clickEvt: function () {
console.log("hey!!");
this.setState({counter: this.state.counter + 1});
return debounced(request(this.props.counter), 3000);
},
render: function () {
return (
<button onClick={this.clickEvt}>hit me</button>;
);
}});
The problem is, the debounced function runs the request in every click that I make in that button. What's the problem?