-3

I'm doing some simple functions using javascript, and I need to create an infinite loop that calls the getMessage() function every 5 seconds. Is there an easy method in achieving this? I searched online and I found that this can be done using the settimeout function. Any suggestions on how to use this? Thanks. Here is this code I created till now...

$(document).ready(function () {

    getMessage();
});

function getMessage() {

    alert("Hello World");

}
Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
N.Cre
  • 167
  • 1
  • 2
  • 13

2 Answers2

3

setTimeout will only alert once, setInterval is what you're looking for.

$(document).ready(function () {
    window.setInterval(getMessage, 5000);
});

function getMessage() {

    alert("Hello World");

}

To stop the interval:

var interval = window.setInterval(getMessage, 5000);
window.clearInterval(interval);
Marco Scabbiolo
  • 7,203
  • 3
  • 38
  • 46
2

function getMessage() {
  document.write("Hello World");
}

function go() {
  getMessage();
  setTimeout(go, 5000);
}

// $(document).ready(function () {
  go();
// });

function getMessage() {
  document.write("Hello World");
}

function go() {
  var lastRun = -5000;
  
  (function tick(now) {
    if(now - lastRun >= 5000) {
     lastRun = now;
     getMessage();
   }
    requestAnimationFrame(tick);
  }());
}

// $(document).ready(function() {
  go();
// });
Ben Aston
  • 53,718
  • 65
  • 205
  • 331