Notes

Show a countdown timer and enable button after the time is up (plain JavaScript)

Edit on GitHub

JavaScript

Example use case

  • SMS verification during registration

JavaScript used

  • setTimeOut()
  • setInterval()
  • clearInterval()
  • document.querySelector()
  • .removeAttribute()

Code

1<p>
2  Resend code in <strong>00:<span id="resend-verification-code-timer">59</span></strong>
3</p>
4<button id="resend-verification-code" disabled>Resend code</button>
5</div>
 1let timerDuration = 60000 // milliseconds
 2let endTime = Date.now() + timerDuration // keep track of the time difference explicitly
 3const resendCodeTrigger = document.querySelector('#resend-verification-code')
 4const resendCodeTimerElement = document.querySelector('#resend-verification-code-timer')
 5
 6// Start countdown timer and show the time passing
 7const setResendCodeTimer = setInterval(() => {
 8  let delta = endTime - Date.now() // milliseconds remaining till endTime
 9  let remainingSeconds = Math.floor(delta / 1000) // convert milliseconds to seconds
10  resendCodeTimerElement.innerHTML = remainingSeconds < 10 ? `0${remainingSeconds}` : remainingSeconds // show 00:07 instead of 00:7
11}, 1000) // update remaining time display every second
12
13function stopResetCodeTimer() {
14  clearInterval(setResendCodeTimer)
15}
16
17// Enable the resend code button after timer duration (60 seconds) is up
18function enableResendCodeButton() {
19  setTimeout(() => {
20    resendCodeTrigger.removeAttribute('disabled')
21    stopResetCodeTimer()
22  }, timerDuration - 1000)
23}
24
25enableResendCodeButton()