John
John

Reputation: 3050

Stop an Ajax call

    $(document).keydown(function(e){
        if (e.keyCode == 37) { 
            move("West");
            return false;
        }
        if (e.keyCode == 38) { 
            move("North");
            return false;
        }
        if (e.keyCode == 39) { 
            move("East");
            return false;
        }
        if (e.keyCode == 40) { 
            move("South");
            return false;
        }
    });

        function move(newDirection)
        {
            var direction = newDirection;

            $.ajax({
                type: "POST",
                url: "ajax/map.php",
                data: { direction: direction },
                success: function(data) {
                    $('#content').html(data);
                }
            });
        }

If I keep down the Left key a while too long, the call will keep coming and coming, and it (won't stop) What I am looking for is to make some delay, or simply just make one call when the key is pressed (or perhaps stop instantly when the key is released) But I'm not sure how. Any suggestions on solution?

Upvotes: 0

Views: 73

Answers (2)

iMoses
iMoses

Reputation: 4348

You can change the keydown event into keyup so it will only trigger when you stop pressing a button. Would that help?

You might also find this thread helpful: Abort Ajax requests using jQuery

I've made an example: http://jsfiddle.net/kdDwd/2/

Upvotes: 1

shershen
shershen

Reputation: 9993

to limit calls per time you should use debounce pattern - here's article about guy writing plugin for this - http://habrahabr.ru/post/60957/ (it's in Russian, hope google translate helps)

Upvotes: 0

Related Questions