1

I'm working on an application that plays multiple sounds controlled by the user. I am trying to adjust the volume of the sounds, which can be done independently. I added a timeout function to the keyup, so it will adjust the volume after 1.5 seconds of no input.

The problem is all the boxes use the same timer, so if you edit multiple within the 1.5 seconds, only the last one gets updated.

I tried to remedy this by using an array to keep track of the separate functions, but realized it wasn't copying the function, just saving a reference to it.

I can't explicitly create variables for each sound as I will let users add their own. Any ideas on how to solve this problem.

I've simplified it here: http://codepen.io/samkeddy/pen/VLKJjJ

//timer 
volDelay = [];

delay = (function(){
        var timer = 0;
        return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
})();

$('body').on('keyup', '.volume', function () {
        soundID = $(this).parent().data('soundid');
        newVol = $(this).val();

        volDelay[soundID] = delay;

        volDelay[soundID](function(){

            console.log('set vol on ' +soundID+ ' to ' +newVol);
            //set volume 
            $('.sound-'+soundID).html(newVol);

         }, 1500 );
});
1
  • Well, looks like you can use Async priorityQueue function for that. Commented May 23, 2015 at 21:22

1 Answer 1

1

You forgot var-ing soundID & newVol, which made them global and you reset them each time.

Also, your use of timers was creating a mess. Simply save the timerID in your array and use that to clear.

//timer 
volDelay = [];

    $('body').on('keyup', '.volume', function () {
            var soundID = $(this).parent().data('soundid');
            var newVol = $(this).val();

      clearTimeout(volDelay[soundID]);
            volDelay[soundID] = setTimeout(function(){

                console.log('set vol on ' +soundID+ ' to ' +newVol);
                //set volume 
                $('.sound-'+soundID).html(newVol);

             }, 1500 );
    });

and a fixed codepen.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, works perfectly when implemented, and is much easier to understand too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.