Reputation: 23
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.
Upvotes: 0
Views: 198
Reputation: 19
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);
Upvotes: 0
Reputation: 2162
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.
Upvotes: 2