I am trying to make React play a sound when a timer gets to 0. The timer runs in a component built with reacts bootstrap modal component.
If the browser tab in which the app is running is inactive, the sound sometimes doesn't get played even if counter reaches 0 until browser tab is clicked. When tab is clicked sound plays properly. (tested in Chrome)
The state.timeLeft variable is being properly updated, I wrote the component to display % of time left as the tabs title and it's obvious sound doesn't get played even if counter hits 0. Any thoughts on what might trigger this behavior ? Your help is appreciated :)
import React, {Component} from 'react'
import {Button, Modal, Image} from 'react-bootstrap'
import doneWav from '../sounds/sunny.wav'
class Pomodoro extends Component {
constructor(props) {
super(props)
this.state = {
timeLeft: this.props.time*60, //time left stored in seconds
}
this.targetDate = Date.parse(new Date()) + this.props.time*60*1000
}
componentDidMount() {
this.intervalId = setInterval( () => {
let timeLeft = ( this.targetDate - Date.parse(new Date()) )/1000
this.setState({timeLeft})
document.title = `${Math.round((timeLeft/(this.props.time*60))*100)}%`
if(timeLeft < 1) {
clearInterval(this.intervalId)
}
}, 500)
}
componentWillUnmount() {clearInterval(this.intervalId)}
render() {
const pomodoroIsRunning = this.state.timeLeft > 1
const playAudio = !pomodoroIsRunning ? <audio src={doneWav} autoPlay/> : null
const title = pomodoroIsRunning ?
`${this.props.activity.title} - ${this.state.timeLeft} sec left` :
`Hurray, job done !`
const button = pomodoroIsRunning ?
<Button variant="secondary" onClick={this.props.stop} className="">Stop</Button> :
<Button variant="primary" onClick={this.props.finish}>Claim Reward</Button>
return (
<>
{ playAudio }
<Modal
