TL;DR;
- Codesanbox link with notes
- Twitch stream, twitch.tv/codesagas during your lunch break, 11 AM MST
- Youtube
This is Easy Right
As a coding educator, I have seen many developers make a timer in js like this
setInterval(function(){
// Do my task every second...
}, 1000)
This will work in most cases but there are some cases that it fails. The main case is giving the user time to do a task. Like a timed test or take a turn in a game.
The issue is that they may get extra time because the action itself takes time to compute. Also, knowing when to stop is tricky.
The solution requires a tad bit more work but is simple enough.
Solution
Just do the interval more regularly. It is easy as a human to get stuck in thinking in seconds because we commonly do that in real life. Computers can handle much smaller time frames. We might have to do a bit more but it gives a better experience.
setInterval(function(){
// Do my task every 50 milliseconds...
}, 50)
Come Watch
This post was explored in more depth during our Twitch stream, twitch.tv/codesagas during your lunch break, 11 AM MST. Come hang out and learn something new with us. We go over most things web development and try to keep it simple. Replays are posted on Youtube in their entirety. And don't forget to follow us on Twitter for more tips, tricks, and updates.
Cover Photo by Veri Ivanova on Unsplash
Top comments (0)