防止ajax回调settimeout每次单击执行一次以上


Prevent ajax callback settimeout from executing more than once per click

我有一个按钮,当你点击它时,它会显示时间,等待5秒,再次显示时间,然后无限期重复。但是,如果您再次单击该按钮,它将再次调用该函数,因此现在有两个ajax调用同时运行。因此,不用等待5秒并显示时间,因为有两个ajax调用同时运行。因此,根据你第二次点击按钮的时间,它可能会等待2秒,显示时间,等待3秒,显示日期,无限期重复。

我曾想过在按钮被点击后使其不可点击,但我无法做到这一点,因为我计划在按钮中添加除ajax setTimeout回调之外的其他功能,如果我使按钮不可点击的话,那就行不通了。所以,我的问题是,有没有办法在调用第二个ajax调用之前取消第一个ajax调用?

test1.php

<style>
#output {
width: 25%;
height: 25%;
border: 1px solid black;
}
</style>
<input type = 'submit' value = 'show time' onclick = "showTime('test2.php', 'output')">
<div id = 'output'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript"> 
function showTime(gotoUrl,output) {
$.ajax({
type: "POST",
url: gotoUrl,
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( output ).innerHTML = data;
setTimeout(function(){showTime(gotoUrl, output)}, 5000);
} //end of success:function(data)
}); //end of $.ajax
} //end of function ajaxFunc(gotoUrl, output)
</script>

test2.php

<?php
date_default_timezone_set('America/New_York');
$time = date('H:i:s');
echo $time;
?>

这需要多次编辑,但我有点仓促。它应该沿着以下几条线:

var $element = $('selector');
//add event handler on click
$element.click(function () {
    //set up indefinite ajax call
    setInterval(function (){
        $.ajax({
           url: url,
           data: somedata,
           method: 'get'
        }).done(function (data) {
           //do something
        });
    }, 5000);
    //now we can remove the click event from the button
    $element.off('click');
});
//now we can add new ones using the reference
$element.on(//do whatever you want);

如果将setTimeout()的响应存储在变量中,则可以在下次使用clearTimeout()方法单击按钮时取消它。

clearTimeout(myShowTime);
myShowTime = setTimeout(function(){showTime(gotoUrl, output)}, 5000);

您可以使用xhr.abort();中止ajax调用的方法如下:

var xhr;
function showTime(gotoUrl, output) {
    if (xhr) {
        xhr.abort();
    }
    xhr = $.ajax({
        type: "POST",
        url: gotoUrl,
        error: function (xhr, status, error) {
            alert(error);
        },
        success:function (data) {
            document.getElementById( output ).innerHTML = data;
            setTimeout(function() {
                showTime(gotoUrl, output)
            }, 5000);
        }
    });
} 

使用jQuery .off()解除绑定一个处理程序:

http://api.jquery.com/off/