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.
Advertisement
Answer
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);