使用jquery发送新的ajax请求之前添加延迟 [英] Add delay before sending new ajax request using jquery

查看:196
本文介绍了使用jquery发送新的ajax请求之前添加延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指向html页面的链接列表.

I have a list of links wich point to html pages.

<ul id="item-list">
    <li><a href="assets/data/item1.html">Item 1</a></li> 
    <li><a href="assets/data/item2.html">Item 2</a></li>
    <li><a href="assets/data/item3.html">Item 3</a></li>
    <li><a href="assets/data/item3.html">Item 4</a></li>
</ul>

而且我有一个javascript(jquery)夹式文档,并将html附加到我的文档中.

And i have a javascript(jquery) wich recives and append the html to my document.

var request;
$('#item-list a').live('mouseover', function(event) {
    if (request)
        request.abort();
        request = null;

    request = $.ajax({
        url: $(this).attr('href'),
        type: 'POST',
        success: function(data) {
            $('body').append('<div>'+ data +'</div>')
        }
    });
});

我尝试过使用setTimeout(),但是它不能像我所说的那样工作.

I've tried to work with setTimeout() but it does not work as i aspected.

    var request, timeout;
$('#item-list a').live('mouseover', function(event) {
    timeout = setTimeout(function(){
        if (request)
            request.abort();
            request = null;

        request = $.ajax({
            url: $(this).attr('href'),
            type: 'POST',
            success: function(data) {
                $('body').append('<div>'+ data +'</div>')
            }
           });
        }, 2000
    );
});

我如何告诉jquery在悬停之前等待(500ms或1000ms或…),然后发送新请求?

How can i tell jquery to wait (500ms or 1000ms or …) on hover before sending the new request?

推荐答案

我认为,也许不应该中止请求,而应该使用变量,例如 processing=false ,将在成功/错误功能中将其重置为false. 然后,如果处理为假,则只能在setTimeout中执行该函数.

I think that perhaps instead of aborting the request, you should control the ajax requests with a variable, for example, called processing=false, that would be reset to false, in the success/error function. Then you would only execute the function in setTimeout, if processing was false.

类似的东西:

var request, timeout;
var processing=false;
$('#item-list a').live('mouseover', function(event) {
  timeout = setTimeout(function() {
    if (!processing) {
      processing=true;
      request = $.ajax({
        url: $(this).attr('href'),
        type: 'POST',
        success: function(data) {
          processing=false;
          $('body').append('<div>'+ data +'</div>')
        }
      });
    }
  }, 2000);
});

这篇关于使用jquery发送新的ajax请求之前添加延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆