0
    $(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?

John
  • 2,900
  • 8
  • 36
  • 65

2 Answers2

1

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/

Community
  • 1
  • 1
iMoses
  • 4,338
  • 1
  • 24
  • 39
  • I would rather like it stop call when the key is released (but instantly make no more calls). Since If i hold for a bit, the character will keep going, some sort of delay might help? Or just stop instantly. – John Jun 13 '12 at 13:18
  • Great example, but it only works once. Then I can't move again when I try to. – John Jun 13 '12 at 13:32
  • Take into consideration that in the example a single click will most likely won't do anything, as the script will be aborted before it has a chance to fetch the ajax response. – iMoses Jun 13 '12 at 14:10
  • I'm just saying, it's stopping as it should do, but then the walking doesn't work anymore. – John Jun 13 '12 at 14:49
0

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)

shershen
  • 9,875
  • 11
  • 39
  • 60