私は jQuery を使用して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>
関数内の AJAX リクエストがclick
正常に実行されると、上記のコードがリロードされます (注: でレンダリングさdata
れるものreplaceWith
は、JavaScript を含め、上記のコードとまったく同じです)。ただし、は「上書き」/「停止」されていないため、.をクリックするたびにsetInterval
ブラウザがもう一度実行されます。実行時に同じことは起こりません。ただし、以前の のクリック量に応じて、がますます実行されるようになります。setInterval
LINK
refreshFunction
LINK
refreshFunction
setInterval
setInterval
AJAX リクエストが成功したときに実行を停止して、1 つだけを実行するにはどうすればよいsetInterval
ですか?