2

I want to be able to call the function work() every 6 seconds. My jQuery code is

function looper(){
  // do something
  if (loopcheck) {           
    setInterval(work,6000);
    }
  else {
    console.log('looper stopped');
  }
}

The problem I am running into is that it loops over work twice quickly, and then it will wait for 6 seconds. i tried using setTimeout with similar results.

What could be causing work to be called twice before the delay works?

iwasrobbed
  • 46,496
  • 21
  • 150
  • 195

3 Answers3

1

setInterval should be avoided. If you want work to be repeatedly called every 6 seconds, consider a recursive call to setTimeout instead

function loopWork(){
    setTimeout(function () {
        work();
        loopWork();
    }, 6000);
}

Then

function looper(){
  // do something
  if (loopcheck) {           
    loopWork()
  }
  else {
    console.log('looper stopped');
  }
}

And of course if you ever want to stop this, you'd save the value of the last call to setTimeout, and pass that to clearTimeout

var timeoutId;
timeoutId = setTimeout(function () {
    work();
    loopWork();
}, 6000);

Then to stop it

clearTimeout(timeoutId);
Community
  • 1
  • 1
Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Noting of course that this doesn't run the function every six seconds, it runs the function and then schedules the next one for six seconds later - so if the function takes one second to run it will run every seven seconds. (Of course most _sensible_ JS code doesn't take a whole second to run, but still...) – nnnnnn Jan 01 '12 at 22:28
0

Use old-style setTimeout()

        var i=0;
        function work(){
            console.log(i++);
        }
        function runner(){
            work();
            setTimeout(runner, 6000);
        }            
        runner();
omakoleg
  • 539
  • 4
  • 6
0

I prefer the following pattern myself I find it easier to follow:

function LoopingFunction() {
    // do the work

    setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}

And if you want to be able to stop it at any point:

var LoopingFunctionKeepGoing = true;
function LoopingFunction() {
    if(!LoopingFunctionKeepGoing) return;
    // do the work

    setTimeout(arguments.callee, 6000); // call myself again in 6 seconds
}

Now you can stop it at any time by setting LoopingFunctionKeepGoing to false.

Luis Perez
  • 27,650
  • 10
  • 79
  • 80