Click here to Skip to main content
15,897,032 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
In this code I have applied the code but the problem is that after the 0 the timer should stops and does not print negative values but it is not stopping. Does anybody know better solution to solve to solve this problem as if there is timer of 60 seconds it will print 60,59,58,57,56 and then start skipping and start showing the values 53, 51, 48 upto 0 and then does not print any value..

What I have tried:

JavaScript
var timeleft = 60;
var n=3;
var t=1;
var Timer = setInterval(function(){
    if(timeleft>56){
        timeleft = timeleft - t;
    }
    else{
        timeleft = timeleft - n;
    } 
    console.log(timeleft);
    if(timeleft <= 0)
        clearInterval(Timer);
},1000);
Posted
Updated 6-Aug-21 1:34am
v3

1 solution

The only negative value printed by your code is -1. That's because you're subtracting three second intervals from 56, which is not divisible by 3.

Once your code hits -1, the timer stops.

If you want to avoid printing -1, change your termination check to:
JavaScript
if (timeLeft < n)
    clearInterval(Timer);
 
Share this answer
 
Comments
[no name] 6-Aug-21 8:01am    
at last checkpoint i want to end it at 0 and does not print negative value. But code it is printing the 2 as after the 5 it should end at the 0
[no name] 6-Aug-21 8:08am    
if any value entered in n variable it at last checkpoint the timer should stops at 0 and does not print negative values and n can be any value.
Richard Deeming 6-Aug-21 8:43am    
You are repeatedly subtracting 3 from 56. 56 is not divisible by 3. Therefore you cannot get to 0. You can either get to 2, or -1.

The only other option is to replace negative values with 0:
if (timeleft > 56){
    timeleft = timeleft - t;
}
else {
    timeleft = timeleft - n;
}

if (timeleft < 0) {
    timeleft = 0;
}

console.log(timeleft);

if(timeleft === 0){
    clearInterval(Timer);
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900