11

Can someone quickly and simply explain to me how to perform an action every couple of seconds using

var timeOut = setTimeout(FunctionName, 5000);

I want to run a function every 5 seconds.

Bharata
  • 13,509
  • 6
  • 36
  • 50
Iladarsda
  • 10,640
  • 39
  • 106
  • 170

6 Answers6

34

As you asked for a method using setTimeout:

function doStuff() {
   console.log("hello!");
   setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);

But it would probably be better to use setInterval:

function doStuff() {
   console.log("hello!");
}
setInterval(doStuff, 5000);
James Allardice
  • 164,175
  • 21
  • 332
  • 312
2

Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.

miku
  • 181,842
  • 47
  • 306
  • 310
1

Use setInterval:

var timeOut = setInterval(nextNotice, 5000);
Igor Dymov
  • 16,230
  • 5
  • 50
  • 56
1
var myFunction = function() { 
     //Do stuff
     AnotherFunction();
};

var timeOut = setInterval(myFunction, 2000);
Rob Stevenson-Leggett
  • 35,279
  • 21
  • 87
  • 141
1

In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.

<html>
  <head>
    <script type="text/javascript">
      var c = 0;
      var t;
      var timer_is_on = false;

      function timedCount() {
        document.getElementById('txt').value = c;
        c = c + 1;
        t = setTimeout(timedCount, 1000);
      }

      function doTimer() {
        if (!timer_is_on) {
          timer_is_on = true;
          timedCount();
        }
      }
    </script>
  </head>
  <body>
    <form>
      <input type="button" value="Start count!" onclick="doTimer()">
      <input type="text" id="txt" />
    </form>
  </body>
</html>
vaidas
  • 514
  • 3
  • 9
  • [W3Schools is not a great resource](http://w3fools.com/). If you are linking an article on another site, please also summarise it here. – lonesomeday Aug 02 '11 at 09:17
  • But the resource has a perfect example: – vaidas Aug 02 '11 at 09:19
  • No, it has a functional example. There are numerous problems with that bit of code that make it a poor example (use of a number as a boolean, use of a string with `setTimeout`, no actual invocation of the code, meaningless variable names). – lonesomeday Aug 02 '11 at 09:27
1

you can do something like:

$(document).ready(function () 
        {
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff 
setTimeout(nextNotice, 5000);
}
Mark Redman
  • 24,079
  • 20
  • 92
  • 147