3

I have this function which updates every 5000ms. However, when I load the page, it waits 5000ms then calls the function for the first time and then waits 5000ms to update it again and again.

I want to make it so, on page load, it instantly calls the function the first time and then waits 5000ms to call it again and again. How can I do this?

setInterval(function() {
    document.getElementById("test").innerHTML = "js works";
}, 5000);
<div id="test"></div>
Kiwa
  • 215
  • 2
  • 10

2 Answers2

1

You could use setTimeout with an IIFE.

(function loop() {
  document.getElementById("test").innerHTML = "js works";
  console.log(new Date().getTime());
  setTimeout(loop, 5000); // Run the loop function for every 5000 ms.
}()); // Run the loop function at first time.

Something like this:

(function() {

  (function loop() {
    document.getElementById("test").innerHTML = "js works";
    console.log(new Date().getTime());
    setTimeout(loop, 5000);
  }());

}());
<div id="test"></div>
1

Use !function IIFE syntax with setTimeout:

!function refresh () {
  document.getElementById("test").innerHTML = Date.now()
  setTimeout(refresh, 5000)
}()
<div id="test"></div>
Afanasii Kurakin
  • 3,330
  • 2
  • 24
  • 26
  • 1
    Further reading for those who haven't seen this pattern: https://stackoverflow.com/questions/5827290/javascript-function-leading-bang-syntax – msanford Mar 17 '19 at 04:10
  • What is reason for `!` before function? – Maheer Ali Mar 17 '19 at 04:11
  • 1
    When using `!` Before a function declaration, it becomes a function expression, so you can call it as if you were executing a function expression. You can see it in this answer: https://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function#5654929. – Danny Fardy Jhonston Bermúdez Mar 17 '19 at 04:21