freeCodeCamp/guide/chinese/javascript/tutorials/how-to-create-a-countdown-t.../index.md

1.2 KiB
Raw Blame History

title localeTitle
How to Create a Countdown Timer 如何创建倒数计时器

如何创建倒数计时器

创建

首先构建countdownTimer函数。

function startCountdown(seconds){ 
  var counter = seconds; 
 
  var interval = setInterval(() => { 
    console.log(counter); 
    counter--; 
 
 
    if(counter < 0 ){ 
 
      // The code here will run when 
      // the timer has reached zero. 
 
      clearInterval(interval); 
      console.log('Ding!'); 
    }; 
  }, 1000); 
 }; 

执行

现在,为了启动计时器,我们提供了startCountdown()其中一个数值作为参数,表示倒计时的秒数。

  startCountdown(10); 
  // Console Output // 
  // 10 
  // 9 
  // 8 
  // 7 
  // 6 
  // 5 
  // 4 
  // 3 
  // 2 
  // 1 
  // 0 
  // Ding! 

实例

Codepen - 倒数计时器

更多资源

使用的方法: