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
  • 12,657
  • 6
  • 32
  • 48
Iladarsda
  • 10,490
  • 39
  • 104
  • 167

6 Answers6

33

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
  • 160,885
  • 21
  • 326
  • 309
2

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

miku
  • 172,072
  • 46
  • 300
  • 307
1

Use setInterval:

var timeOut = setInterval(nextNotice, 5000);
Igor Dymov
  • 15,840
  • 4
  • 48
  • 54
1
var myFunction = function() { 
     //Do stuff
     AnotherFunction();
};

var timeOut = setInterval(myFunction, 2000);
Rob Stevenson-Leggett
  • 34,539
  • 21
  • 86
  • 139
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
  • 23,351
  • 20
  • 92
  • 141