Thierry Lam
Thierry Lam

Reputation: 46264

How do I delay ajax calls to the server in javascript?

For the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var delay = (function() {
        var timer = 0;
        return function(callback, ms) {
            clearTimeout(timer);
            timer = setTimeout(callback, ms);
        };
    })();

    $("div#main").on("keyup", "input[name=code]", function() {
        delay($.getJSON("/some-url/", function(data) {
            console.log("here");
        }), 2000);
    });

});
</script>

<div id="main">
  <input name="code" />
</div>

Does anyone know why I'm getting the javascript error

Uncaught SyntaxError: Unexpected identifier

I am trying to delay sending keyup data to the server.

Upvotes: 1

Views: 1645

Answers (3)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

You've just forgotten to pass delay a function definition. Just tweak your event handler slightly (everything else stays the same):

$("div#main").on("keyup", "input[name=code]", function() {
    delay(function() { // <-----
        $.getJSON("/some_url/", function(data) {
            console.log("here");
        });
    }, 2000);
});

Example: http://jsfiddle.net/f7F7c/

Upvotes: 2

azzy81
azzy81

Reputation: 2269

Does this help you at all: http://jsfiddle.net/ZYXp4/8/

This simply adds a delay when typing each time the keyup action is fired. try the jsfiddle to see it in action. You can do your ajax call after the delay has occurred no probs ^^

<input id="in" type="text"/>
<div id="out"></div>

var typingTimer;
var doneTypingInterval = 1000;

//on keyup, start the countdown
$('#in').keyup(function(){
    clearTimeout(typingTimer);
    if ($('#in').val) {
        typingTimer = setTimeout(function(){
            //do stuff here e.g ajax call etc....
             var v = $("#in").val();
             $("#out").html(v);
        }, doneTypingInterval);
    }
});

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Looks like autocomplete to me? Try this instead...

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var timer = 0;

    function runAjax() {
        $.getJSON("/some-url/", function(data) {
            console.log("here");
        });
    }

    $("div#main").on("keyup", "input[name=code]", function() {
        clearTimeout(timer);
        timer = setTimeout(runAjax, 2000);
    });

});
</script>

<div id="main">
  <input name="code" />
</div>

Upvotes: 0

Related Questions