Jquery self-call function loop
-
27-10-2019 - |
Question
I'm trying to check whether my self-calling jquery function did the job done but what happened is that the result keep multiplying on each self calling.
HTML
<span id="checkit"></span>
Javascript
$(function(){
callme();
});
function callme(){
$('#checkit').append("callme loaded<br />");
setInterval("callme()", 5000);
}
Normally, here's my result for the codes.
onLoad.
callme loaded
5 seconds later
callme loaded <from previous
callme loaded
another 5 seconds later
callme loaded <from previous
callme loaded <from previous
callme loaded
callme loaded
callme loaded
callme loaded
Sorry for the crappy explanation. I've been thinking really hard why this stuffs happened. If anyone could explain what I did wrong, or the solution for this. Please help - This problem kept bugging me for days.
Solution
Each time you call callme
, you are creating a new interval that will call callme
again. You can clear the previous interval using clearInterval
or use setTimeout
instead of setInterval
.
function callme(){
$('#checkit').append("callme loaded<br />");
setTimeout(callme, 5000);
}
OTHER TIPS
setInterval is not setTimeout. You are not clearing the interval, so they are compounding.
You need to check if the #checkit element has been created. And, you need to use a timeout (which only calls once) instead of an interval (which goes on and on):
function callme(){
$('#checkit').append("callme loaded<br />");
if (!document.getElementById('checkit'))
setTimeout(callme, 5000);
}
Reference for learning: window.setTimeout