So, we have seen the requirements where in which we are required to send the data to the server on an event that might be a click, hover, mouseEnter or anything.
So let us consider we are writing a click event for a button. So the basic code for the same would look something like this:
Now suppose you are saving/posting the data to the server on every click, in that case if suppose, user clicked the button 2 3 times, it will save the same data 3 times with different ids.
In order to handle this we have 2 options:
Explanation:
Happy Coding :)
So let us consider we are writing a click event for a button. So the basic code for the same would look something like this:
1 2 3 4 5 | $(document).ready(() => { $("#btn").on('click', async (event) => { // do some api calls or anything }) }) |
Now suppose you are saving/posting the data to the server on every click, in that case if suppose, user clicked the button 2 3 times, it will save the same data 3 times with different ids.
In order to handle this we have 2 options:
- either disables the button once you click and enables it once the callback returns
- Write a debounce function to handle accidental clicks
Lets see first how debounce function is written.
1 2 3 4 5 6 7 8 9 10 11 12 13 | const debounce = (fn, delay) => { let timeoutId; return (...args) => { if(timeoutId) clearTimeout(timeoutId); timeoutId = setTimeout(() => fn(...args),delay) } } $(document).on('ready', async() => { $('#btn').on('click', debounce(e=> { console.log('bye bye') }, 2000)) }) |
Explanation:
- In this code, we have first created a higher order function named debounce that is taking 2 params, the callback function and a delay to reset the functionality if, someone triggered the event twice.
- The debounce function is returning a function that is calling our callback passed at line 5.
- Now, instead of giving the callback directly to the event, we are calling debounce and passing our callback function implementation as well as the delay that is going to wait for certain time, before resetting the timeout.
Happy Coding :)
Not meeting the demands of the consumers
ReplyDeletewifikill pro apk
Dababy
HOTSCHEDULES LOGIN
apa pool login