[英]How can I stop a setInterval to run after executing a AJAX request that replaces that setInterval in the DOM with another setInterval?
我正在使用jQuery,在执行AJAX请求(返回包含相同setInterval
的相同代码)时,在停止工作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请求成功运行时,上述代码将重新加载( 注意 : replaceWith
的呈现data
与上述代码完全相同 ,包括JavaScript)。 但是, setInterval
不会“覆盖” /“停止”,因此,每当我单击LINK
时,浏览器就会比setInterval
多运行一次。 运行refreshFunction
时不会发生相同的情况。 但是,取决于上一次在LINK
上单击的次数,即使refreshFunction
会使setInterval
越来越多地运行。
如何在AJAX请求成功时停止setInterval
的运行,以便仅运行一个setInterval
?
在执行更换之前,您将需要清除计时器。 为此,您还需要在click
回调中也可以访问timer变量。 在这种情况下,我已将计时器设置为全局计时器,但是您可以通过其他方法来实现,这取决于您自己。
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.