Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

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 173 views
1 answer 162 views
1 answer 177 views
2 answers 230 views
2 answers 223 views
2 answers 168 views
168 views asked Oct 11, 2024 by avibootz
1 answer 156 views
156 views asked Oct 11, 2024 by avibootz
...