0

This is the first time I'm trying something like this. When I click the button, I want to set the new value and then fire the function, but only after a delay. The reason for this, is that I want to stop the user from spamming the button and firing the function every time. From my research, I think I need to put the function that needs to be timed out in a useEffect and listen for when amount changes?, not in the onClick like I have here. But I'm running into some problems. Any help would be greatly appreciated

        <StyledQuantityButton disabled={ amount <= 0 } 
            onClick={() => {
                const newValue = amount - 1;
                setAmount(newValue);
                setTimeout(iWantToDelayThisFunction(someDataToBePassed, moreData), 2000)}
            } >
            &mdash;
        </StyledQuantityButton>
  • 1
    `setTimeout(iWantToDelayThisFunction(), 2000)}` => `setTimeout(iWantToDelayThisFunction, 2000)}`. You don't want to call the function immediately and pass its return value to `setTimeout`, you want to pass it to `setTimeout` so that it can call it later for you. – ggorlen Jul 31 '21 at 18:25
  • Oh I see.. but what if that function requires parameters? I probably should have made that clear. I'll update the question – DonegalBoyVancouver Jul 31 '21 at 18:29
  • Please [read the link](https://stackoverflow.com/a/7137443/6243352) and use the search feature. The answer is always out there somewhere! – ggorlen Jul 31 '21 at 18:31
  • 1
    Oh, duh, I see it right there. (It's early in the morning lol) Thank you! – DonegalBoyVancouver Jul 31 '21 at 18:37
  • I've added an anonymous function and now it only fires when I need it. But I notice that if I spam the button, the function will delay, but then when the delay is over, it will fire the amount of times I clicked. Is there a way to make sure the function only fires once? – DonegalBoyVancouver Jul 31 '21 at 19:40
  • [Perform debounce in React.js](https://stackoverflow.com/questions/23123138/perform-debounce-in-react-js). See [here](http://demo.nimius.net/debounce_throttle/) for a visualization of debounce to make sure it's what you want – ggorlen Jul 31 '21 at 20:01
  • Yeah I gave that a try and it just seems to be doing exactly what setTimeout is doing. Still firing multiple times after the delay. Obviously I'm missing something here, so I'll just keep digging. Thanks for the help! – DonegalBoyVancouver Jul 31 '21 at 20:27

0 Answers0