[英]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.