简体   繁体   中英

Constantly check if date is in the past

I want to check if selected date is in the past in 'for loop'. But if I use 'for loop' it stops other code from running. How can I constantly check if date is in the past and not stopping other code from running?

for (var now = new Date();;) {
   if (selectedDate < now) { 
      // some code
   }
}

console.log('1') // code that's not running.

JavaScript is fully synchronous and single-threaded. Therefore, your code is getting "locked-up" or stuck at the for loop you have referenced.

You need to use setInterval . For example:

 // For demonstration purposes. var selectedDate = new Date(); // The code inside of this function will run every 1 second (or 1,000 milliseconds) setInterval(function () { var now = new Date(); if (selectedDate < now) { console.log("Selected date is in the past!"); } }, 1000); console.log('1') // This code runs now because JavaScript is not caught executing the for loop. 

Lot of solutions for resolve this problem. You can use an Observable if ou use RXJS. Else you can use a simple interval with an arrow function or a simple funtion and define repeat time interval in millisecond :

setInterval(repeatFunc,intervalInMillisecond);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM