第一种:

  1. <body>
  2. <button id="btn">3</button>
  3. <script>
  4. var num =3;
  5. var btn = document.getElementById("btn");
  6. var timer = setInterval(function(){
  7. num--; //-1
  8. console.log(num)
  9. if(num>=0){
  10. btn.innerHTML = num;
  11. }else{
  12. clearTimeout(timer)
  13. }
  14. },1000)
  15. </script>
  16. </body>

第二种:

  1. <body>
  2. <button id="btn">3</button>
  3. <script>
  4. /* 递归:函数调用函数自身 */
  5. var btn = document.getElementById("btn");
  6. var num = 3;
  7. function go() {
  8. setTimeout(function () {
  9. num--; //
  10. if (num >= 0) {
  11. btn.innerHTML = num;
  12. go();
  13. }
  14. }, 1000)
  15. }
  16. go();
  17. </script>
  18. </body>

五秒倒计时小练习:

  1. <body>
  2. <button id="btn">发送验证码</button>
  3. <script>
  4. var num =5;
  5. var btn = document.getElementById("btn");
  6. var timer
  7. /* 1、让按钮进入倒计时的状态(不能点击的状态)*/
  8. btn.onclick = function(){
  9. this.disabled = true;
  10. this.innerHTML = num;
  11. /* 2、每过1s num-- */
  12. timer = setInterval(function(){
  13. num--
  14. if(num>=0){
  15. btn.innerHTML = num;
  16. }else{
  17. btn.disabled = false;
  18. btn.innerHTML = "发送验证码";
  19. num =5;
  20. clearInterval(timer);
  21. }
  22. },1000)
  23. }
  24. /* 使用setTimeout去实现 */
  25. </script>
  26. </body>