Javascript decrement value overtime with setInterval & clearing it?

时间:2017-04-10 00:43:10

标签: javascript

I'm trying to fade in the volume of an audio element over time.

Below is the javascript I mocked up. So the scenario is, when a button is clicked, I want this function to run.

The volume decreases over time by -0.1. When the volume is 0, clear the interval... The function runs, but the interval isn't clearing.. what am I doing wrong?

var setVolume = function(){
    var volume = 1; 
    var fadeVolume = setInterval(function(){
        volume -= 0.1;
        audio[0].volume = volume;
        console.log(volume);
    }, 100);
    if(volume === 0) {
        clearInterval(fadeVolume);
    }
}

Thanks in advance.

2 个答案:

答案 0 :(得分:2)

It's the floating point number representation at fault (and also where the clearInterval was used as mentioned in other answers). Equivalence of floating point numbers is often a problem and the best way around it in situations like this is not to use them if you can help it!

> x = 1
1
> x -= 0.1
0.9
> x -= 0.1
0.8
> x -= 0.1
0.7000000000000001

I would recommend using integers instead.

Like this: https://jsfiddle.net/6wfk0tgj/

var volume = 100; 
var fadeVolume = setInterval(function(){
    volume -= 10;
    // If audio really needs to be a float then you could do:
    audio[0].volume = volume/100;
    console.log(volume);
    if(volume === 0) {
        clearInterval(fadeVolume);
    }
}, 100);

答案 1 :(得分:0)

You need to call the clearInterval function within the interval callback:

var setVolume = function(){
    var volume = 1; 
    var fadeVolume = setInterval(function(){
        volume -= 0.1;
        audio[0].volume = volume;
        console.log(volume);
      if(volume === 0) {
          clearInterval(fadeVolume);
      }
    }, 100);

}