How to run while loop for N seconds in TypeScript

1 Answer

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

let startTime = Date.now(); // Get the current time
const duration = 3000; // Duration in milliseconds (e.g., 3000ms = 3 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 16:30:21 GMT+0300 (Israel Daylight Time)" 
"Fri Oct 11 2024 16:30:22 GMT+0300 (Israel Daylight Time)" 
"Fri Oct 11 2024 16:30:23 GMT+0300 (Israel Daylight Time)" 
 
*/

 



answered Oct 11, 2024 by avibootz

Related questions

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