Sunny
Sunny

Reputation: 1215

setinterval and clearinterval not working properly

I am creating the app for the samsung smart tv. In that i want the volume bar to appear for 5 seconds after that it has to hide. If the user continuously presses the volume, it has to hide after 5 secs the user stops pressing the button. I tried like this:

var vt;
    if($("#volume").css('display')=='none'){
        $("#volume").show(); 
        vt=setInterval(function(){$("#volume").hide();},5000);

    }
    else{
        clearInterval(vt);
        vt=setInterval(function(){$("#volume").hide();},5000);
    }

when the user presses the button it is not clearing the interval instead it is creating the instance for every click

Upvotes: -1

Views: 600

Answers (2)

Ravi Hamsa
Ravi Hamsa

Reputation: 4721

This is bit sophisticated solution, picked from underscore library.

var debounce = function(func, wait, immediate) {
    var timeout, result;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) {
                result = func.apply(context, args);
            }
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) {
            result = func.apply(context, args);
        }
        return result;
    };
};


var clickHandler = function(){
    $("#volume").hide();
}

var debouncedClickHandler = debounce(clickHandler, 5000);

$('body').on('click', debouncedClickHandler) //change this line to your click handler

Now you don't have to do any thing, clickHandler will get called only after 5 seconds delay from last call to debouncedClickHandler

Upvotes: 0

Praveen
Praveen

Reputation: 2419

Try this:

if($("#volume").css('display')=='none'){
    $("#volume").show(); 
    vt = setTimeout(function(){$("#volume").hide();},5000);
}
else{
    clearTimeout(vt);
    vt = setTimeout(function(){$("#volume").hide();},5000);
}

Upvotes: 1

Related Questions