DEV Community

webit
webit

Posted on

Coding task: implement mechanism that increments counter once 2 seconds

During the last technical interview, I received a coding task. The task description says:

click event from button element should change count value not more often than 2 seconds

Seems simple. The initial code looked like this:

Initial task code

The first notable issue: clicking the button reloads the whole page; that's bad behavior, but we will fix it later - no worries.


First iteration

Looking at a Counter's code, I thought about creating some kind of lock. We will set a lock on click and release it after 2 seconds. Clicking the button when the lock is set - won't increment the counter value.

I used useState for storing the lock flag and useEffect with the cleanup function to release it when the component was removed from the DOM.
Additionally, since we click the button I added Event.preventDefault() to prevent page reload on button click.

My code looked like this:

First iteration code

That code worked perfectly fine... but was far from perfect.


Second iteration

Then, I realized I had made heavy over-engineering here.
Instead of using the useState hook, I could use useRef to store timeoutID (value returned by setTimeout). By using this solution, I knew that when the value stored in useRef hook is truthy (not null/undefined) I could not increment the value. In that case, I also added useEffect with cleanup (to remove running setTimeout callback). Finally, I've added type="button" attribute to the button - I was told I can do this to prevent page reloads. That attribute makes the button "has no default behavior, and does nothing when pressed by default". Now the code looked much cleaner and was still working correctly:

Second iteration code

In both cases, you can click the button to implement counter value once per 2 seconds. Clicking multiple times won't increment the value many times and only once when 2 seconds pass since the last increment.


Lessons learned:

  • iterate solutions (you can find better ones after a while)
  • button[type="button"] functionality (I missed it, and it's so easy to use)

I'm wondering how would you resolve this coding task. What would you improve / change / do better? Let me know, I'm super curious :)

You can find (initial) code task in codesandbox

Top comments (0)