How to run while loop for N seconds in Node.js

1 Answer

0 votes
function sleep(seconds) {
    seconds = (+new Date) + seconds * 1000;
    while ((+new Date) < seconds);
}

let startTime = Date.now(); // Get the current time
const duration = 4000; // Duration in milliseconds (e.g., 4000ms = 4 seconds)
const endtime = startTime + duration;
  
while (startTime < endtime) {
    sleep(1); // Sleep for 1 second
    startTime = Date.now();
    console.log(new Date(startTime).toString());
}

         
 
/*
run:
 
Fri Oct 11 2024 09:57:38 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:57:39 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:57:40 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:57:41 GMT+0000 (Coordinated Universal Time)
 
*/

 



answered Oct 11, 2024 by avibootz
edited Oct 11, 2024 by avibootz

Related questions

1 answer 118 views
1 answer 115 views
1 answer 119 views
2 answers 161 views
2 answers 157 views
2 answers 116 views
116 views asked Oct 11, 2024 by avibootz
1 answer 98 views
98 views asked Oct 11, 2024 by avibootz
...