Tariq Husain
Tariq Husain

Reputation: 566

Do something after two second of keyup

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');
        }
    })
})

Upvotes: 9

Views: 7859

Answers (5)

Samir Rahimy
Samir Rahimy

Reputation: 2890

If you want to do something after a period of time and that time could be reset after a specific event like keyup, the best solution is made with clearTimeout and setTimeout methods:

// declare the timeout variable out of the event listener or in global scope
var timeout = null;

$("#some-id-to-bind-event").keyup(function() {
    clearTimeout(timout); // this will clear the recursive unneccessary calls
    timeout = setTimeout(() => {
         // do something: send an ajax or call a function here
    }, 2000);
    // wait two seconds

});

Upvotes: 1

Nikhil Malik
Nikhil Malik

Reputation: 478

If your user is typing continuously like 20 characters then ? setTimeout will call after time (after your defined seconds). If you want most correct way then why not use debounce.

$(function(){

var default_text = $('#text-type').text(),
  text_counter_1 = 0,
  text_counter_2 = 0;

 // This function is not debounced, but instead bound directly to the event.
function text_1() {
  var val = $(this).val(),
  html = 'Not-debounced AJAX request executed: ' + text_counter_1++ + ' times.'
  + ( val ? ' Text: ' + val : '' );

  $('#text-type-1').html( html );
};

// This function is debounced, and the new, debounced, function is bound to
// the event. Note that in jQuery 1.4+ a reference to either the original or
// debounced function can be passed to .unbind to unbind the function.
function text_2() {
  var val = $(this).val(),
  html = 'Debounced AJAX request executed: ' + text_counter_2++ + ' times.'
  + ( val ? ' Text: ' + val : '' );

  $('#text-type-2').html( html );
};

// Bind the not-at-all debounced handler to the keyup event.
$('input.text').keyup( text_1 );

// Bind the debounced handler to the keyup event.
$('input.text').keyup( $.debounce( 250, text_2 ) ); // This is the line you want!

// Trigger the callbacks once to show some initial (zero) values.
text_1();
text_2();
});

Blog Here is live example
Blog 2

Upvotes: 1

Harpreet Singh
Harpreet Singh

Reputation: 2671

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

Upvotes: 13

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4749

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>

Upvotes: 1

Sameer
Sameer

Reputation: 705

hope this will help...

 $("#input").keyup(function(){
     var x=$("#input").val();
     setTimeout(function(){
         if(x==$("#input").val()) {
             alert('ajax call going');
         }
     }, 3000);
});

Upvotes: 2

Related Questions