Javascript 如何将此代码放入可重用函数中?
我在stackoverflow上发现了这段代码,它会慢慢淡出音频轨道。它工作得很好。我发现,如果不进行复制和粘贴,它的结构很难重复使用,因为该函数在自身内部调用自己。代码如下:Javascript 如何将此代码放入可重用函数中?,javascript,function,Javascript,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 s
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;
})
你的问题是什么?您是否在将其保存到文件和使用
标记时遇到问题,或者…?因此您希望使用迭代而不是递归有用于tweening的库,tweening部分是可重用的,tweening是特定于应用程序的,它说“未捕获引用错误:未定义FadeVorume”因为它还没有被制作出来,我正在给它打电话。我想把这个函数放在一个名为preGameContent的对象中,并在任何我想淡出轨迹的地方调用它。preGameContent.fadeVolume(…);它说“uncaughtreferenceerror:fadeVolume没有定义”,因为它还没有被创建,我正在调用它。我想把这个函数放在一个名为preGameContent的对象中,并在任何我想淡出轨迹的地方调用它。preGameContent.fadeVolume(…);