1

I have input in my React Class Component:

changeVal(event) {
  console.log(event.keyKode)
}
...

return(
   <input onKeyDown={event => this.changeVal(event)} />
)

How can I call function on keyDown with 500ms debounce without lodash?

I tried next thing:

debounce = (callback, delay) => {
    const timerClear = () => clear = true;
    var clear = true;
    return event => {
        if (clear) { 
            clear = false;
            setTimeout(timerClear, delay);
            callback(event);
        }
    }
}

return(
   <input onKeyDown={event => this.debounce(this.changeVal, 500)} />
)

But this is does not work at all.

Volodymyr Humeniuk
  • 3,411
  • 9
  • 35
  • 70
  • [Perform debounce in React.js](https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js)??? – gaetanoM Aug 15 '19 at 13:05

2 Answers2

1

Try

const debounce = (func, wait = 500) => {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(this, args);
    }, wait);
  };
}
Morlo Mbakop
  • 3,518
  • 20
  • 21
0

The return value of debounce function should be used as the handler directly. Check an example here: https://codesandbox.io/s/musing-dust-iy7tq

class App extends React.Component {
  changeVal(event) {
    console.log(event.keyCode)
  }

  debounce = (callback, delay) => {
    const timerClear = () => clear = true;
    var clear = true;
    return event => {
        if (clear) { 
            clear = false;
            setTimeout(timerClear, delay);
            callback(event);
        }
    }
}

  render() {
    return(
       <input onKeyDown={this.debounce(this.changeVal, 1500)} />
    )
  }
}
Carlos Frias
  • 523
  • 7
  • 12