Home > Enterprise >  Blurry Loading setInterval
Blurry Loading setInterval

Time:08-26

Im working on 50 day 50 js projects. https://github.com/bradtraversy/50projects50days/tree/master/blurry-loading

Regarding the blurry loading. I wonder why the setInterval works when the brower loads the page, without calling the function? How the int variable and setInterval worked?

Thank you in advance - jsnoob


const int = setInterval(myCallback, 20);

function myCallback() {
  load  ;
  if (load > 99) {
    clearInterval(int);
  }}```

CodePudding user response:

The interval starts on the line when you declare your int constant.
In fact this line

const int = setInterval(myCallback, 20);

Is exactly the same as this line

setInterval(myCallback, 20);

Except that the former saves the id number, say 3, of the interval so that you can stop it later.

To declare a function that starts an interval when called, do it like this:

const int = ()=>{setInterval(myCallback, 20);}
// The following line will not start the interval immediately.
// You can later call int() to start the interval.
int();
// NOTE: this will not save a reference to the interval's id number.
  • Related