简体   繁体   中英

Mirroring function to do the opposite

I have this event to turn my music of by fading it out

    $(bgMusic).on('timeupdate', function () {
    var vol = 1,
        interval = 250;
    if (bgMusic.volume == 1) {
        var intervalID = setInterval(function () {
            if (vol > 0) {
                vol -= 0.05;
                bgMusic.volume = vol.toFixed(2);
            } else {
                clearInterval(intervalID);
            }
        }, interval);
    }
});

I now want the same thing for turning the music on.

I have tried creating the opposite like this:

    $(bgMusic).off('timeupdate', function () {
    var vol = 0,
        interval = 250;
    if (bgMusic.volume == 0) {
        var intervalID = setInterval(function () {
            if (vol < 0) {
                vol += 0.05;
                bgMusic.volume = vol.toFixed(2);
            } else {
                clearInterval(intervalID);
            }
        }, interval);
    }
});

Where am I going wrong?

If you change:

if (vol < 0) {

to:

if (vol < 1) {

... I think the volume should gradually increase until it meets it maximum value of 1, hence giving you the "fade in" effect you ask for.

Not sure about your code but I think you don't want to use the off function in your second example.

jQuery off:

Description: Remove an event handler.

So try your second code with on to, since you want to register to the event, not remove it.

since your vol is 0 , it doesnot goes inside the if condition.. if (vol < 0) {... it should be

   if (vol < 1) {
            vol += 0.05;
            bgMusic.volume = vol.toFixed(2);
        } else {
            clearInterval(intervalID);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM