我如何将此代码放入可重用的函数中?

时间:2013-08-02 02:52:06

标签: 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 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;
})

1 个答案:

答案 0 :(得分:2)

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