Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

longestdrive's avatar

Trying to debounce a click event in a livewire component

I have a component that enables a user to add a score for a player. The input is tied to a model and I've added buttons either side to increment or decrement the score value.

Once the score is updated it calls a couple of methods to calculate points and update a leaderboard, the score entry is also stored in a database.

I'm trying to debounce the click event so that a user could click a couple of times to increase/decrease the score and only then store to the database and update the leaderboard.

I've looked up creating a custom function but failing to get it to work and scrapped that and also now trying to use the debouce modifier in Alpine.js but that stops all the functionality of the button.

Here's the buttons and related input:

HOw can I best apply a debounce to the call to updateScore method?

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To debounce the click event in your Livewire component, you can use a combination of Alpine.js and JavaScript's setTimeout function. The idea is to delay the execution of the updateScore method until the user has stopped clicking for a specified amount of time.

Here's how you can implement it:

  1. Create a Debounce Function: First, create a debounce function in your Alpine.js component. This function will delay the execution of the updateScore method.

  2. Modify the Click Event: Use this debounce function in your button click events.

Here's an example of how you can achieve this:

Explanation:

  • debounceUpdateScore Function: This function uses setTimeout to delay the execution of the updateScore method. The clearTimeout function is used to reset the timer if the user clicks again before the delay is over.

  • Debounce Delay: The delay is set to 300 milliseconds in this example, but you can adjust it to suit your needs.

By using this approach, the updateScore method will only be called once the user has stopped clicking for the specified delay period, reducing the number of calls to the server and improving performance.

Please or to participate in this conversation.