Saturday 5 January 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...