2

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.

datuamizan
  • 23
  • 1
  • 4

3 Answers3

3

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);
}
Will
  • 19,661
  • 7
  • 47
  • 48
0

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

N Rohler
  • 4,595
  • 24
  • 20
0

setInterval is not setTimeout. You are not clearing the interval, so they are compounding.

Joe
  • 80,724
  • 18
  • 127
  • 145