1

I'm using a function called refreshinbox which will run every 3 sec. But when a user types something on a search input field then this function should stop. When he clear (empty input) then again this function work for every 3 sec.

I'm using keyup,keydown function to take the length of the text input. I can't use live event because I'm using jQuery 1.10.2 version. Using if else condition I'm trying to achieve the requirements. But the problem is else condition is working every time. I don't know whats wrong with my code. Please help.

var myVar = setInterval(function(){ refreshinbox() }, 3000);
function refreshinbox(){
    $(".refreshfirebasecount").load(location.href + " .refreshvalue");
    $(".refreshfirebasecount2").load(location.href + " .refreshvalue2");
};

$('#searchinbox').keyup(updateCount);
$('#searchinbox').keydown(updateCount);
function updateCount() {
    var cs = $(this).val().length;
    if(cs > 0) {
        $('.searchiconinbox-close').css({'display':'block'});
        clearInterval(myVar);
    } else {
        $('.searchiconinbox-close').css({'display':'none'});
        var myVar = setInterval(function(){ refreshinbox() }, 1000);
    }
}
acmsohail
  • 903
  • 10
  • 32

1 Answers1

0

In your function updateCount you're using myVar for storing an interval. You should expose it outside of that function. I mean:

var myVar;
function updateCount() {
    var cs = $(this).val().length;

    clearInterval(myVar);
    if(cs > 0) {
        $('.searchiconinbox-close').css({'display':'block'});
    } else {
        myVar = setInterval(refreshinbox, 1000);
        $('.searchiconinbox-close').css({'display':'none'});
    }
}
sunpietro
  • 2,059
  • 4
  • 24
  • 42