node js while loop with settimeout
In Node.js, you can use a while loop in combination with the setTimeout function to create a delayed execution of code. Here's an example of how this can be done:
let count = 0;
function incrementCount() {
count++;
console.log("Count:", count);
if (count < 5) {
setTimeout(incrementCount, 1000);
}
}
incrementCount();
Explanation for each step:
- We declare a variable
count
and initialize it with a value of 0. - We define a function called
incrementCount
which increments thecount
variable by 1 and logs the current value ofcount
. - Inside the
incrementCount
function, we check if the value ofcount
is less than 5. If it is, we use thesetTimeout
function to delay the execution of theincrementCount
function by 1000 milliseconds (1 second). This creates a delay between each iteration of the loop. - Finally, we call the
incrementCount
function to start the loop.
Each time the incrementCount
function is called, it increments the count
variable by 1 and logs the current value of count
. If the value of count
is less than 5, the function schedules itself to be executed again after a delay of 1 second. This process repeats until the value of count
reaches 5, at which point the loop terminates.
Note: This example assumes that you are running the code in a Node.js environment where the console.log
function is available for logging output.