2

I am trying to create a clapping button similar to the Medium's button. My strategy is using a setTimeout function as is defined in the following paragraph.

addClap: function () {
    this.setState({clap: this.state.clap + 1, now: this.state.now + 1});

    return setTimeout(() => {
        return sendClaps(this.props.item.url, this.state.now);
    }, 3000);
}

Unfortunately, this doesn't work as I want. I would like to let the User hit the button how many times they want to and when they stop, send the clap-counter value to the backend.

urb
  • 924
  • 1
  • 13
  • 28
  • I'm not sure I completely understand what you are attempting to do, but I believe you are looking for something like [debounce](https://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript)? – rmlan Mar 09 '18 at 18:36
  • Interesting, I want to hit clapping button and until I am hitting that button no request is made to the server otherwise we will overload the server with many requests when we could do it in one request. – urb Mar 09 '18 at 18:45
  • 3
    Ok, then debounce is exactly what you want. Perhaps [this](https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js) may be of assistance? – rmlan Mar 09 '18 at 18:45
  • Can you elaborate what this means? "send the amount of claps in the counter if after 3 seconds the user stopped to hit the button."? You want to send 1 clap if they hover the button for more than 3 seconds like the way the medium button works? OR do you want the user to click the clap button multiple times in 3 seconds and then after 3 seconds you send all of the claps in one request? – Chase DeAnda Mar 09 '18 at 21:26
  • @ChaseDeAnda You were right, I rewrote the question. Answering to your question, it's the second option. I want to let the user to click the clap button multiple times and then after 3 seconds of users' inactivity send all of the claps in one request. – urb Mar 09 '18 at 22:37
  • @rmlan Your answer was correct. I solved the problem with a debounce function. Thanks! feel free to add it as an answer. – urb Mar 15 '18 at 10:05

0 Answers0