gpt4 book ai didi

javascript - 我如何将这段代码放入可重用的函数中?

转载 作者:行者123 更新时间:2023-11-30 17:56:14 24 4
gpt4 key购买 nike

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

关于javascript - 我如何将这段代码放入可重用的函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18007974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com