Issue
I am trying to create a countdown timer that starts at 10 seconds and counts down every second until 0. Once that happens it should start again from 10 seconds and count down to 0. This should happen for 4 times in total. I also want to achieve this using a return in the method.
This is what I have tried, I am getting an undefined result in the console log and also am not sure if the retries should just be a for loop around this method
Service file
//Countdown timer
public countdownTimer(retries, timeLeft) {
setInterval(() => {
if(timeLeft > 0) {
timeLeft--;
} else {
timeLeft = 10;
}
}, 1000);
return timeLeft;
}
Component where I will be using the method
console.log(this.timeUtils.countdownTimer(4, 10));
Can anyone please assist?
Solution
The issue with your current approach is that setInterval
is asynchronous and return timeLeft
is executed immediately, not waiting for the interval to finish. This is why you're seeing undefined
in your console log. Additionally, your current implementation doesn't consider the retries
parameter, which should control how many times the countdown repeats.
To achieve your desired functionality, you can use recursion and a combination of setTimeout
and setInterval
. Here's an updated version of your method:
// Service file
// Countdown timer
public countdownTimer(retries, timeLeft) {
return new Promise(resolve => {
const countdown = () => {
let interval = setInterval(() => {
if (timeLeft > 0) {
console.log(timeLeft);
timeLeft--;
} else {
clearInterval(interval);
retries--;
if (retries > 0) {
timeLeft = 10;
countdown();
} else {
resolve();
}
}
}, 1000);
};
countdown();
});
}
// Component where I will be using the method
this.timeUtils.countdownTimer(4, 10).then(() => {
console.log('Countdown completed');
});
Explanation:
- The
countdownTimer
method now returns a Promise, which resolves when all retries are completed. - The
countdown
function handles a single countdown fromtimeLeft
to 0 and is called recursively for each retry. setInterval
is used to count down every second. WhentimeLeft
reaches 0, it clears the interval and checks if there are more retries left.- If retries are left, it resets
timeLeft
to 10 and callscountdown
again. - Once all retries are completed, the Promise is resolved, and you can handle the completion in the
.then()
method in your component.
This setup should provide the desired countdown behavior and allows you to handle the completion of the entire countdown process effectively.
Answered By - andkho
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.