-1

I've wrote this code and it surprises me.

I do not understand why the function is called but executed only first 2 lines, then setInterval waits 1 second and execute return statement.

Please, somebody explain it to me :)

let div = document.getElementById("div1");
const updateTime = () => {
  let seconds = 0;
  if (seconds === 0) div.textContent = `0 sekund`;
  return () => {
    seconds++;
    div.textContent = `${seconds} sekund`;
  }
}
setInterval(updateTime(), 1000);
<div id="div1"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236

2 Answers2

1

You execute updateTime() immediately, it performs the first two lines and then, also immediately, returns the function that is run first time 1 second later and then every second after that

Please read the comments I wrote in the code:

let div = document.getElementById("div1");
const updateTime = () => {
  // next two lines executed by updateTime() immediately
  let seconds = 0; // these are remembered because you create a closure
  if (seconds === 0) div.textContent = `0 sekund`;

  // NOW the following function is returned and will be what is 
  // executed for the rest of the life of the setInterval
  // The first time this returned function is called is in one second from now
  return () => { // this creates a closure. It is a good way to handle vars
    seconds++; // this is known only to the function 
    div.textContent = `${seconds} sekund`;
  }
}
setInterval(
  updateTime(), // execute this IMMEDIATELY 
  1000 // execute whatever is returned from updateTime in intervals of 1 seconds 
 ); 
<div id="div1"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

The updateTime function runs when you call it, which is when you type updateTime().

All of it runs.

The part of it after the return keyword is syntax which defines another function. It doesn't run immediately, because you haven't done anything to call it.

That other function is returned.

You are passing that function to setInterval which calls it every second.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Yes, you are right... I should take a break after 16h+ marathon with JS... seems like i dont understand simply words anymore. Thanks. –  Oct 19 '18 at 12:51