HonorableTones
HonorableTones

Reputation: 138

Countdown Timer in Vanilla Javascript without using a function

I have a project where I need to do a countdown timer, However no function can be used. I know that this can be done with a setInterval, however, most of the documentation I have found shows a function being used in conjunction. W3schools has a great example, however, it used a function. I know how I would do it with

I have already written some code, and was able to display the minutes and seconds, however, cannot get it to actually count down. is there a way to do this without a function?

const timeSpan = document.getElementById('timer');

// Get Time Now
var timeMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeMinutes * 60 * 1000);
var distance = deadline - currentTime;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

timeSpan.innerHTML = minutes + 's' + seconds;

This shows the minutes and seconds, but without the setInterval or setTimeOut it wont count down like a normal countdown timer. For the project it needs to count down from ten minutes and at the end alert the user that is is expired and that they will need to refresh the page.

Upvotes: 1

Views: 3687

Answers (2)

XTRUST.ORG
XTRUST.ORG

Reputation: 3392

<script>    
var timer   = (mins) => {
                        
    const timeSpan  = document.getElementById('timer');
    const now       = new Date().getTime();
    const deadline  = mins * 60 * 1000 + now;
    
    setInterval(() => {
        var currentTime = new Date().getTime();
        var distance = deadline - currentTime;
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
                                
        timeSpan.innerHTML = minutes + ' min. ' + seconds + ' s.';
        
        if (minutes <=0 && seconds <=0) {
                alert('Time is over');
                return false;
        }

    }, 1000);   
 }
 
 timer(10);

</script>
<span id="timer"></span>

Upvotes: -1

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

You need to move some things out of the function as you are resetting the timer on every interval. You should avoid storing your times as Date objects as well since you only need the timestamps.

const timeSpan = document.getElementById('timer');

const mins = 10;
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;


setInterval(() => {
  var currentTime = new Date().getTime();
  var distance = deadline - currentTime;
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  timeSpan.innerHTML = minutes + 's' + seconds;
}, 500)
<span id=timer></span>

Upvotes: 6

Related Questions