9

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');
        }
    })
})
Tariq Husain
  • 559
  • 5
  • 23

5 Answers5

13
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

Harpreet Singh
  • 2,651
  • 21
  • 31
  • :) Thanks for the code best code so far but i really dnt know how its working. i cant understand the flow – Tariq Husain Dec 14 '15 at 07:32
  • @TariqHusain Please read inline comments. If still it is not clear I will try to explain it. – Harpreet Singh Dec 14 '15 at 07:35
  • you have already clear the interval clearInterval(_changeInterval): then how it still going in setInterval function after two second – Tariq Husain Dec 14 '15 at 07:41
  • @TariqHusain. Yes I am clearing, but at the same time I am creating a new Interval too – Harpreet Singh Dec 14 '15 at 07:42
  • http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_setinterval_clearinterval2 Hi @harpreet could you see in above example while clearing interval and we are passing variable bt why there color toggling stop same like your code they are creating new interval while clearing . and second question inside the setinterval function why we need to clear the interval again ? – Tariq Husain Dec 14 '15 at 08:58
  • @TariqHusain We are clearing bcoz setInterval will repeat itself after 2 seconds. In your case it will make AJAX call after every 2 seconds repeatedly. In the example you have provided toggling is continuous bcoz of setInerval which is repeating itself after every 300ms. They don't need to clear and set the interval again because they need to perform their operation for each interval. In our case, we need to perform operation only once that's why we are clearing it before its execution starts. – Harpreet Singh Dec 14 '15 at 09:05
  • thanks for explain :) i will practice interval for better understanding – Tariq Husain Dec 14 '15 at 09:29
  • @TariqHusain glad to help. Even I was very surprised on this solution when I got it from SO, so easy and clean. Even I spend a lot of time understanding it at that time how actually it is working. – Harpreet Singh Dec 14 '15 at 09:36
2

hope this will help...

 $("#input").keyup(function(){
     var x=$("#input").val();
     setTimeout(function(){
         if(x==$("#input").val()) {
             alert('ajax call going');
         }
     }, 3000);
});
Tsumannai
  • 134
  • 2
  • 12
Sameer
  • 705
  • 10
  • 25
  • this wont help me. according to your answer if i typed Stack it wills end ajax call 5 times but 3 sec late. i just want one time not 5 times – Tariq Husain Dec 14 '15 at 06:09
  • it wont call ajax five time as you the variable x is checking the value of the input which..so the ajax request will only go when the user stops typing..that's why the 3 sec delay – Sameer Dec 14 '15 at 06:12
  • bro code works good only one problem still call is going two time. even i type 5 words even 7 call going two times. its alerting two times. – Tariq Husain Dec 14 '15 at 06:18
  • 1
    haha :D but it will be more good if you could find the reason why its going two times. :) – Tariq Husain Dec 14 '15 at 06:38
  • try this... var y $("#wwf").keyup(function(){ var x=$("#wwf").val(); setTimeout(function(){ if(x==$("#wwf").val() && y==0) { y=1; //set the value of y so that only one ajax request goes $.post('..xx' + Math.random() , { }, function (result) { y=0;//change the value of y to 0 }); else{ y=0; } }, 1000); }); – Sameer Dec 14 '15 at 06:59
  • i think last one is better this new code got so many error and so much messy :( – Tariq Husain Dec 14 '15 at 07:04
  • just use a variable which will tell you that a ajax request is made and reset the variable in the ajax response – Sameer Dec 14 '15 at 07:06
  • im still debugging and trying to understand why its alerting two time . if i couldnt find i will still accept your answer as you said two is better than 5 :D – Tariq Husain Dec 14 '15 at 07:06
  • For me it is alerting only once. May be you have pressed any alt key(Developers usually press Alt+Tab for Toogling applications) – Sanjay Kumar N S Dec 14 '15 at 07:09
  • thanks bro for great help and solution :) yea finally its worked thanks you. but still dont know why last code was alerting two times. – Tariq Husain Dec 14 '15 at 07:10
  • what do you mean by last code...which one worked :P..using 2 variables worked? – Sameer Dec 14 '15 at 07:12
  • 1
    using two variable :) .. i mean why single variable code was not working why it was alerting two times sometime? – Tariq Husain Dec 14 '15 at 07:12
  • i guess while waiting 3 sec..the keyup request was queued and after that both requests were executed..as the value remained same – Sameer Dec 14 '15 at 07:15
1

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>
Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38
  • You may be missed the first line: var lastTime = new Date(); – Sanjay Kumar N S Dec 14 '15 at 06:17
  • still not working its not waiting for two second. whenever i up key after pressing it alert ajax call going. – Tariq Husain Dec 14 '15 at 06:20
  • I did like, if the user continuously pressing the key, it won't send the ajax call but it calls if the key up is happening after 2 second from the very previous key up. – Sanjay Kumar N S Dec 14 '15 at 06:26
  • Quoting from your post: "check that if user didnt press any again for two second after he press any key" – Sanjay Kumar N S Dec 14 '15 at 06:27
  • that should not be like "but it calls if the key up is happening after 2 second from the very previous key up" it should automatically send ajax call if user didnt press any key within two second of last pressed key .. according to your comment user have to press key again. – Tariq Husain Dec 14 '15 at 06:29
  • you mean i should give this title ? check that if user didnt press any again for two second after he press any key – Tariq Husain Dec 14 '15 at 06:30
  • Oh.. ok, Then what you mean by ,"Thus i can save lot of ajax call every time hw press a key ." – Sanjay Kumar N S Dec 14 '15 at 06:34
  • i mean to say without condition if i type stack(5 char) that mean ajax call will go 5 times. i just want to send it one time if user stop typing for more than two second. – Tariq Husain Dec 14 '15 at 06:37
  • :) ajax call going two times and im not being able to find why two times.. try "stackoverflow" this word it will alert two times. – Tariq Husain Dec 14 '15 at 06:51
  • Did you press ENTER key when it is alerted which also trigger the keyup event – Sanjay Kumar N S Dec 14 '15 at 06:54
  • Did you press any key after that, Put the below code and tell what is alerting $("#input").keyup(function(event){ alert(event.which); //remaining code...... }); – Sanjay Kumar N S Dec 14 '15 at 06:59
  • For me it is alerting only once. May be you have pressed any alt key(Alt+Tab for Toogling applications) – Sanjay Kumar N S Dec 14 '15 at 07:02
1

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

Nikhil Chaudhary
  • 478
  • 4
  • 16
1

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

});
Samir Rahimy
  • 2,580
  • 1
  • 18
  • 10