Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something after two second of keyup

Tags:

jquery

ajax

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');
        }
    })
})
like image 961
Tariq Husain Avatar asked Dec 14 '15 05:12

Tariq Husain


3 Answers

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

like image 92
Harpreet Singh Avatar answered Nov 17 '22 05:11

Harpreet Singh


hope this will help...

 $("#input").keyup(function(){
     var x=$("#input").val();
     setTimeout(function(){
         if(x==$("#input").val()) {
             alert('ajax call going');
         }
     }, 3000);
});
like image 2
Sameer Avatar answered Nov 17 '22 04:11

Sameer


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>
like image 1
Sanjay Kumar N S Avatar answered Nov 17 '22 04:11

Sanjay Kumar N S