Stop setInterval

You need to set the return value of setInterval to a variable within the scope of the click handler, then use clearInterval() like this: var interval = null; $(document).on(‘ready’,function(){ interval = setInterval(updateDiv,3000); }); function updateDiv(){ $.ajax({ url: ‘getContent.php’, success: function(data){ $(‘.square’).html(data); }, error: function(){ clearInterval(interval); // stop the interval $.playSound(‘oneday.wav’); $(‘.square’).html(‘<span style=”color:red”>Connection problems</span>’); } }); … Read more

Calling a function every 60 seconds

If you don’t care if the code within the timer may take longer than your interval, use setInterval(): setInterval(function, delay) That fires the function passed in as first parameter over and over. A better approach is, to use setTimeout along with a self-executing anonymous function: (function(){ // do some stuff setTimeout(arguments.callee, 60000); })(); that guarantees, … Read more

Changing the interval of SetInterval while it’s running

You could use an anonymous function: var counter = 10; var myFunction = function(){ clearInterval(interval); counter *= 10; interval = setInterval(myFunction, counter); } var interval = setInterval(myFunction, counter); UPDATE: As suggested by A. Wolff, use setTimeout to avoid the need for clearInterval. var counter = 10; var myFunction = function() { counter *= 10; setTimeout(myFunction, … Read more

How can I make setInterval also work when a tab is inactive in Chrome?

On most browsers inactive tabs have low priority execution and this can affect JavaScript timers. If the values of your transition were calculated using real time elapsed between frames instead fixed increments on each interval, you not only workaround this issue but also can achieve a smother animation by using requestAnimationFrame as it can get … Read more

setTimeout or setInterval?

They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to … Read more