
Photo by AgĂȘ Barros on Unsplash
Timers
Learn how to repeatedly play the same sound file on mobile using setInterval in JS.
2023-05-05T13:53-07:00
Okay fine. I admit it. I'm not perfect. And before you inevitably try to convince me otherwise, I'll reveal my biggest flaw in the workplace: I'm not good at taking breaks.
It's hard to stop myself when I'm caught in a creative flow. I was also raised to be an overachiever, so for a long time I saw taking more breaks as being less productive. Only after pushing myself to pre-2007 Arianna Huffington stress levels did I realize the importance of taking regular breaks.
My favorite method for achieving this is the Pomodoro Timer. It alerts you to take a short break after a fixed interval of time. I find I stay the most creative by taking five minute breaks after every 25 minutes or so of work. At first 25 minutes didn't even seem like enough time to get settled, but I was amazed to discover how much I could get done in that span when I quickly and regularly refreshed myself. It improved my workflow so much that I decided to design my own Pomodoro Timer.
The implementation wasn't anything too complicated — just alternating setIntervals marked by two distinct sounds. I also used this approach to create a more flexible workout timer that announces what number repetition the user is starting. All of this worked great on desktop, but mobile was a different story.
It turns out on mobile you can automatically play a JavaScript Audio object (such as the timer's beep), but without further user interaction (such as clicking a button) the sound only plays once. This was a big problem for a web app that played automated beeps after several intervals of work and break time.
After identifying the issue above with the help of Stack Overflow, it occurred to me that I could automatically play the same sound multiple times on mobile devices if I created arrays full of separate Audio objects that play the same sound. Iterating through these identical playbacks would trick the browser into thinking it's playing a brand new sound automatically for the first time.
/*
Mobile browsers will not play sounds repeatedly with setInterval.
Create arrays of Audio objects to play separately.
*/
const breakBeeps = [],
workBeeps = [];
for (let i = 0; i < 24; i++) {
breakBeeps.push(new Audio("./audio/break-start-beep.mp3"));
workBeeps.push(new Audio("./audio/break-end-beep.mp3"));
}
I'm happy to say this hack worked, and now I can successfully use both timers when I'm away from my desktop. If you haven't ever tried integrating a productivity timer into your workflow, I highly suggest you do. Let me know how it goes by sending an email to al@fern.haus.