我正在使用jQuery,在执行返回包含相同setInterval
的相同代码的AJAX请求时停止工作setInterval
时遇到一些麻烦。那就是:
鉴于我有以下代码:
<div id="test_css_id">
<a id="link_css_id" href="test_url.html">LINK</a>
<script type="text/javascript">
$('#link_css_id').click(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'PUT',
success: function(data) {
$('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
}
});
});
$(document).ready(function() {
var refreshTimer;
function refreshFunction(){
$.ajax({
url: 'test_url.html',
type: 'GET',
success: function(data) {
$('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
},
complete: function(data) {
clearInterval(refreshTimer); // Note: This'd not stop the setInterval.
}
});
}
refreshTimer = setInterval(refreshFunction, 1000); // milliseconds
});
</script>
</div>
当click
函数中的AJAX请求成功运行时,将重新加载上述代码( note :data
中呈现的replaceWith
< em>完全与上面的代码相同,包括JavaScript)。但是,setInterval
不会“覆盖”/“停止”,因此每次点击setInterval
时,浏览器会再次运行LINK
。 refreshFunction
运行时不会发生同样的情况。但是,根据之前点击LINK
的数量,即使refreshFunction
导致setInterval
运行的次数越来越多。
如何在AJAX请求成功时停止setInterval
运行,以便只有一个setInterval
正在运行?
答案 0 :(得分:1)
在执行更换之前,您需要清除计时器。为此,您还需要在click
回调中访问计时器变量。在这种情况下,我已经将计时器设置为全局,但是还有其他方法可以做到,我会把它留给你。
<div id="test_css_id">
<a id="link_css_id" href="test_url.html">LINK</a>
<script type="text/javascript">
var refreshTimer; //******************** Timer is now global
$('#link_css_id').click(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'PUT',
success: function(data) {
//************* Clear interval if it exists before replacing code.
clearInterval(refreshTimer);
$('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
}
});
});
$(document).ready(function() {
function refreshFunction(){
$.ajax({
url: 'test_url.html',
type: 'GET',
success: function(data) {
$('#test_css_id').replaceWith(data); // Replaces all code including JavaScript with the response data (note: the response data is exactly the same as the code shown here).
},
complete: function(data) {
clearInterval(refreshTimer); // Note: This'd not stop the setInterval.
}
});
}
refreshTimer = setInterval(refreshFunction, 1000); // milliseconds
});
</script>
</div>