I have the code as per below. This retrieves some data to use for the counter including a variable for the reload interval – this is NOT used below in order to rule out an issue with the data retrieval, I have hard coded a 10 second interval instead but the problem remains.
All works fine for the intial page load and also for one interval, then everything goes haywire, the calls are made with no delay and the counter cannot react before the next call is made, both the onAnimationStopped and the setInterval appear to be ignored eventually leading to a total hang.
There is some sort of a loop happening somewhere but despite trawling for a few hours none of the answers I have found related to setInterval/Ajax calls answer this issue.
Please note I have also tried setTimeout but this exhibits identical behaviour.
Any help appreciated.
(Only tested using FF and Chrome at present – same issue in both).
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="js/jquery.flipCounter.1.2.js" type="text/javascript"></script>
</head>
<body>
<div id="counter">
<input type="hidden" name="counter-value" value="0" />
</div>
<script type="text/javascript">
/* <![CDATA[ */
jQuery(document).ready(doAjax());
function doAjax()
{
jQuery.ajax({
async: false,
type: "POST",
url: "counterData.php",
dataType: "json",
cache: false,
success: function (data){
doTheCounter(data);
}
})
}
function doTheCounter(data)
{
var scrollfromnumber = data.scrollfromnumber;
var displaynumber = data.displaynumber;
var reloadinterval = data.reloadinterval;
jQuery("#counter").flipCounter({
number: scrollfromnumber,
numIntegralDigits:6,
numFractionalDigits:0
});
jQuery("#counter").flipCounter("startAnimation", {
end_number: (displaynumber),
easing:jQuery.easing.easeInOutCubic,
duration:5000,
onAnimationStopped: function(){
setInterval(doAjax,10000);
}
});
}
/* ]]> */
</script>
</body>
</html>
Do not send ajax requests or start animations with a
setInterval,setIntervaldoesn’t allow for slow browsers/networks or network connection failures. UsesetTimeoutinstead.Also,
$(document).ready(doAjax());should be$(document).ready(doAjax);The reason your code fails with setInterval is because you never cleared the previous interval, you just started another one every time, so first you sent one request, then 2, 4, 8, 16, 32, 64, etc. until the browser crashes.
UPDATE: