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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to run while loop for N seconds in JavaScript

2 Answers

0 votes
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
 
(async function() {
    let starttime = Date.now();
    const seconds = 3 * 1000; // Convert seconds (3) to milliseconds
    const endtime = starttime + seconds;
 
    while (starttime < endtime) {
        await sleep(1000); // Sleep for 1 second
        starttime = Date.now();
        console.log(new Date(starttime).toString());
    }
})();
 
 
/*
run:
 
Fri Oct 11 2024 09:04:58 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:04:59 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:05:00 GMT+0000 (Coordinated Universal Time)
 
*/

 



answered Oct 11, 2024 by avibootz
edited Oct 11, 2024 by avibootz
0 votes
function sleep(seconds) {
    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 09:47:45 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:47:46 GMT+0000 (Coordinated Universal Time)
Fri Oct 11 2024 09:47:47 GMT+0000 (Coordinated Universal Time)
 
*/

 



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

Related questions

1 answer 154 views
1 answer 148 views
1 answer 150 views
1 answer 134 views
2 answers 191 views
2 answers 147 views
147 views asked Oct 11, 2024 by avibootz
1 answer 122 views
122 views asked Oct 11, 2024 by avibootz
...