Sunday, 10 April 2016

javascript - setInterval vs while(true) with delay

Task is to log and increase a variable i = 0 both on initial call and every further second.



Common approach is to use setInterval



const interval = () => {
let i = 0;
console.log(i++);


setInterval(() => {
console.log(i++);
}, 1000);
};

interval();


More exotic way would be to use async infinite loop:




Lets assume we have a delay function



const delay = ms => new Promise(resolve => setTimeout(resolve, 1000));


Then we can utilize it in while(true) loop



const loop = async () => {
let i = 0;

while (true) {
console.log(i++);
await delay(1000);
}
};

loop();


I would really like to know which way is more preferable and why. Thank you.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...