[英]How would i put this code into a re-usable function?
我在stackoverflow上發現了這段代碼,它逐漸淡出了音軌。 它運作良好。 它的結構使我很難在沒有復制和粘貼的情況下重復使用,因為該函數在自身內部進行調用。 這是代碼:
function fadeVolume(volume, callback) {
//change the volume by factor each time
//will check if setTimeout is used to loop as well as wait, as it seems so here
var factor = 0.02,
speed = 50;
if (volume > factor) {
setTimeout(function () {
fadeVolume((gameController.myAudio.preGameTrack.volume -= factor), callback);
}, speed);
} else {
(typeof (callback) !== 'function') || callback();
}
};
fadeVolume(gameController.myAudio.preGameTrack.volume, function () {
preGameContent.ready = true;
//stop the music altogether
gameController.myAudio.preGameTrack.pause();
gameController.myAudio.preGameTrack.currentTime = 0;
})
除gameController.myAudio.preGameTrack
之外的所有語句都將保留。
將其存儲在變量中並傳遞。如果在這種情況下進行交談,應可重用。
function fadeVolume(track, factor, speed, callback) {
//change the volume by factor each time
//will check if setTimeout is used to loop as well as wait, as it seems so here
if (track.volume > factor) {
setTimeout(function () {
fadeVolume((track.volume -= factor), callback);
}, speed);
} else {
(typeof (callback) !== 'function') || callback();
}
};
var track = gameController.myAudio.preGameTrack,
factor = 0.2,
speed = 50;
fadeVolume(track, factor, speed, function () {
preGameContent.ready = true;
//stop the music altogether
track.pause();
track.currentTime = 0;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.