3

I have an input box on which there is an ajax request on every key press. so if i enter word "name" there will be 4 successful request. So i actually want only the latest request of executed. so if i enter word "name" there will be only one request which will be the last one.

and i also have a solution for this (this is a simple example with click method)

JS script

var callid = 1;

function ajaxCall (checkval ){
    if(checkval == callid){
        $.ajax({
            type: 'post',
            url: baseurl + "test/call_ajax",
            data: {
                val: "1"
            },
            success: function(data) {
                console.log(data)
            }
        });
    }
}

function call(){
    var send = callid+=1;
    setTimeout( function(){ ajaxCall(send)  } , 500);
}

html script

<a href="#" onclick="call()" > Call ajax </a>

This is working perfectly. But i was think if there is way to refine it a little bit more.

Any ideas :)

Iori
  • 660
  • 1
  • 10
  • 19

3 Answers3

4

I am sure you are looking some better intent technique for event dispatching.

var eventDispatcher = null;
$('.textbox').keyup(function(){
   if(eventDispatcher) clearTimeout(eventDispatcher);
   eventDispatcher = setTimeout(function(){
       $.ajax({ ... });
   }, 300);
});
Shoaib Nawaz
  • 2,302
  • 4
  • 29
  • 38
3

You could do your ajax inside of a setTimeout. So you don't need to declare and check an additional variable or write another function like call()

$(document).ready(function () {
    var timer;
    $('#fillMe').keypress(function () {
        clearTimeout(timer);
        timer = setTimeout(function () {
            //replace this with your ajax call
            var content = $('#fillMe').val();
            $('#result').text('You will only see this if the user stopped typing: ' + content);
        }, 1000); // waits 1s before getting executed
    });
});

<input type="text" id="fillMe">
<div id="result"></div>

On every keypress event this clears the timeout and immediately creates a new timeout. This means the content of the setTimeout function only gets executed if the user stopped typing for at least 1 second. Of course 1 second is just the value for the example purpose. You can change it to whatever you want or think is a good time (like 500ms)

See my jsfiddle

SirDerpington
  • 11,260
  • 4
  • 49
  • 55
1

setTimeout returns an id that you can store and use to clear the previously set timer:

var timerId;

function call() {
    if (timerId !== undefined) {
        clearTimeout(timerId);  
    } 

    timerId = setTimeout( function() { ajaxCall(send) }, 500);
}

The result of this should be that the ajaxCall method will be called 500ms after the last letter is entered.

disperse
  • 1,216
  • 10
  • 22