I just want to achieve that. if user is searching keyword example "stackoverflow" i just want send a ajax call after that . Not every time he press any key. Thus i can save lot of ajax call every time hw press a key .
Im trying to check that if user didnt press any again for two second after he press any key then i am sending ajax call. but i don't know what to use interval or set time out please help and hope you can understand what i trying to explain . Thanks
here is my little code.
$(document).ready(function(){
    var counter = 0;
    $("#input").keyup(function(){
        var myInterval = setInterval(function () {
            ++counter;
        }, 1000);
        if(myInterval > 2)
        {
            alert('ajax call going');
            clearInterval(myInterval);
        }
        else
        {
            alert('doing nothing');
        }
    })
})
                var _changeInterval = null;
$("#input").keyup(function() {
    // wait untill user type in something
    // Don't let call setInterval - clear it, user is still typing
    clearInterval(_changeInterval)
    _changeInterval = setInterval(function() {
        // Typing finished, now you can Do whatever after 2 sec
        clearInterval(_changeInterval)
    }, 2000);
});
Note: Code taken from SO few months back, don't remember the link
Edit:
Check this jsFiddle. Check comments in the Code and output in console for better understading
hope this will help...
 $("#input").keyup(function(){
     var x=$("#input").val();
     setTimeout(function(){
         if(x==$("#input").val()) {
             alert('ajax call going');
         }
     }, 3000);
});
                        Try this:
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<input type="text" id="input"> 
<script>
$(document).ready(function(){
    $("#input").keyup(function(){
       var str = $(this).val();
       setTimeout(function(){
            if(str == $("#input").val()) {
                alert('ajax call going');
            }
       }, 2000);
    });
});
</script>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With