vydimitrov / react-countdown-circle-timer

Lightweight React/React Native countdown timer component with color and progress animation based on SVG

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Alert sound plays several times when the remaining time less than 5

berkaygurbuz opened this issue · comments

I want to play a sound If the time is less than 5 and it repeats 5 times every seconds. When I use my method I saw that every miliseconds it goes inside of remainingTime and it plays more than 5. Is there any way to figure out ?

    timeFormat = (remainingTime) => {

        if (remainingTime <= 5) {
            if (this.state.playSound) {
                this.playSound();
            }
        }

        var leftTime = '';
        const minutes = Math.floor(remainingTime / 60);
        const seconds = remainingTime % 60;
        leftTime += '' + minutes + ':' + (seconds < 10 ? '0' : '');
        leftTime += '' + seconds;
        return leftTime;
    }

    repeatAudio = async () => {
        this.sound.setPositionAsync(0);
        await this.sound.playAsync();
        this.soundCounter++;
        if (this.soundCounter === 5) {
            this.stopRepetition();
        }
    }

    stopRepetition =async () => {
        clearInterval(this.timer);
        await this.sound.pauseAsync();
        this.state.playSound = true;  //set playSound true to enter the if statement.
        this.soundCounter = 0;
    }

    playSound = () => {
        this.state.playSound = false;   
        this.timer = setInterval(this.repeatAudio, 1000);
    }

Hey, you will need to keep track of the previous state and fire the sound when it changes. I'd do something like this:

import { uesRef } from 'react'
...

const remainingTimeRef = useRef()

...

if (remainingTime <= 5) {
  if (this.state.playSound && remainingTimeRef.current !==  remainingTime  ) {
    this.playSound();
  }

  remainingTimeRef.current = remainingTime
}