2017-04-10 27 views
0

我試圖淡化音頻元素的音量隨着時間的推移。使用setInterval和清除它來減少值超時值?

下面是我嘲笑的JavaScript。所以這個場景是,當點擊一個按鈕時,我想讓這個函數運行。

體積隨時間減少-0.1。當音量爲0時,清除間隔...該函數運行,但間隔不清除..我做錯了什麼?

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); 
    } 
} 

在此先感謝。

+4

如果你回答這個問題,我想你會看到這個問題:在當前的代碼,* *當你清除的時間間隔? –

回答

2

這是有過錯的浮點數表示(也作爲地方在其他的答案中提到的clearInterval使用)。浮點數的等價性往往是一個問題,在這種情況下,最好的解決方法是不使用它們,如果你可以幫助它的話!

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

我會建議使用整數代替。

像這樣: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); 
+0

嘿謝謝你......這似乎是問題所在。我最初確實清除了setInterval中的區間。不幸的是,音頻音量似乎只取0和1之間的值。 – giantqtipz

+1

我修改了我的答案來應對 – dpwrussell

+1

或者簡單地將條件設置爲if(音量<= 0)。 – RobG

0

你需要調用區間回調中調用clearInterval函數:

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); 

}