简体   繁体   中英

Ajax delay is not working

$(document).ready(function() {
   setInterval($("#to").on("change keyup paste click mouseout", function() {
      $.get('ajaxSearch.php', $("#form").serialize(), function(data) {
         $('#result').html(data);
      });
   }, 3000);
});

ajax delay or setTimeout is not working. I want to delay on input field and run ajax after 3 sec but it is not working.

You should use setTimeout to delay the ajax request.

And if one of change keyup paste click mouseout event fired, you just cancel the previous delay and create a new one.

$(document).ready(function() {
   var timer_id;
   $("#to").on("change keyup paste click mouseout", function() {
      if (timer_id) {
          clearTimeout(timer_id);
      }
      timer_id = setTimeout(function() {
         $.get('ajaxSearch.php', $("#form").serialize(), function(data) {
            $('#result').html(data);
         });
      }, 3000);    
   });
});

Your syntax is wrong, also the setInterval() should be in the handler

$(document).ready(function () {
    var interval;
    $("#to").on("change keyup paste click mouseout", function () {
        if (interval) {
            return
        };
        setInterval(function () {
            $.get('ajaxSearch.php', $("#form").serialize(), function (data) {
                $('#result').html(data);
            });
            interval = undefined;
        }, 3000);
    });
});

Also if there is already a interval in progress, we need not have to add another call.

In your case you set deley to event handling ( and whyy you use setInterval but not setTimeout ? )

try

$(document).ready(function() {
    $("#to").on("change keyup paste click mouseout", function() {
        setTimeout(function(){
            $.get('ajaxSearch.php', $("#form").serialize(), function(data) {
                $('#result').html(data);
            });
        }, 3000);  
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM