最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I make a delay for sending an ajax request? - Stack Overflow

programmeradmin1浏览0评论

Here is my code:

$("input").on('keydown', function(){
    $.ajax({
        url :  '/files/tags_autoplete.php',
        dataType : 'JSON',
        success : function (tags) {
            $("ul").html(tags.output);
        }
    });
});

My code suggests some tags (the ones that have a matched substring with what the user has written so far) to user as an autoplete box when he is typing his tags.

What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes something, my script sends 9 ajax requests which seems like a nightmare.

Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?

Here is my code:

$("input").on('keydown', function(){
    $.ajax({
        url :  '/files/tags_autoplete.php',
        dataType : 'JSON',
        success : function (tags) {
            $("ul").html(tags.output);
        }
    });
});

My code suggests some tags (the ones that have a matched substring with what the user has written so far) to user as an autoplete box when he is typing his tags.

What's my problem? My current code sends a new ajax request per each keydown. For example, if the user writes something, my script sends 9 ajax requests which seems like a nightmare.

Anyway, how can I handle that? I mean do I need to implement a delay for sending? Something like "don't send the request until 1 sec after last character inserted"? or is there any better idea?

Share Improve this question asked Sep 22, 2016 at 19:11 Martin AJMartin AJ 6,70712 gold badges71 silver badges137 bronze badges 2
  • You might consider jQuery UI autoplete. It has your requested functionality built in. jqueryui./autoplete. It might not be worth using just for autoplete, but it's worth a look. – Jason P Commented Sep 22, 2016 at 19:32
  • @JasonP Thank you for the link you provided .. but I seen that before .. and yes exactly as you said, using it just for autoplete isn't affordable. though I heard we can download every part of jQuery UI we need (for example, we can download only autoplete part) – Martin AJ Commented Sep 22, 2016 at 20:11
Add a ment  | 

1 Answer 1

Reset to default 9

You could create a simple throttle mechanism

$("input").on('keydown', function(){

    clearTimeout( $(this).data('timer'); )

    var timer = setTimeout(function() {
      $.ajax({
          url :  '/files/tags_autoplete.php',
          dataType : 'JSON',
          success : function (tags) {
              $("ul").html(tags.output);
          }
      });
    }, 500);

    $(this).data('timer', timer);
});
发布评论

评论列表(0)

  1. 暂无评论