2
votes

I have this code to do Fade In and Out the audio of the video tag each time I execute the code.

  var allVideos = document.getElementsByTagName('video');
           if (0 < allVideos[0].volume && allVideos[0].volume <= 1){
             fadeOutFunction();
             console.log("Entered first if statment");
}   else if (allVideos[0].volume == 0) {
             fadeInFunction();
};

        function fadeOutFunction() {
         var value = 0.01;
         var myVar = setInterval(myTimer, 10);
         function myTimer() {


         if(allVideos[0].volume != 0){
            allVideos[0].volume -= value;
         } else if(allVideos[0].volume == 0){
             clearInterval(myVar);
         }
         }
        }
           function fadeInFunction() {
         var value = 0.01;
         var myVar = setInterval(myTimer, 10);
         function myTimer() {
         allVideos[0].volume += value;
         if(allVideos[0].volume == 1){
             clearInterval(myVar);
         }
         }
           }

Here is the code:

The code works fine and I can fade out the video. But each time I execute the function I get this error :

Uncaught DOMException: Failed to set the 'volume' property on 'HTMLMediaElement': The volume provided (-5.30825e-16) is outside the range [0, 1]. at myTimer

Uncaught DOMException: Failed to set the 'volume' property on 'HTMLMediaElement': The volume provided (-3.08781e-16) is outside the range [0, 1]. at myTimer

The last one continues to run with my interval too.

1
It looks like you're running into some floating point error. I would recommend stopping the interval if .volume is less than or equal to 0 not just equal. With floating points, you typically want to check a range not an exact value to avoid this type of issue.Zach Woods

1 Answers

4
votes

You're dealing with a floating-point arithmetic approximation error.

For instance, 0.03 - 0.01 - 0.01 - 0.01 will give you -3.469446951953614e-18.

Replace

allVideos[0].volume += value;

by

allVideos[0].volume = Math.min(1, allVideos[0].volume + value);

and

allVideos[0].volume -= value;

by

allVideos[0].volume = Math.max(0, allVideos[0].volume - value);