1、开启定时器
timeout:暂停; 超时。
interval: (时间上的) 间隔,间隙,间歇。
<script> // 1. setInterval setInterval(function() { console.log('继续输出'); }, 1000); </script>
2、案例:京东倒计时
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> div { margin: 200px; } span { display: inline-block; width: 40px; height: 40px; background-color: #333; font-size: 20px; color: #fff; text-align: center; line-height: 40px; } </style> </head> <body> <div> <span class="hour">1</span> <span class="minute">2</span> <span class="second">3</span> </div> <script> // 1. 获取元素 var hour = document.querySelector('.hour'); // 小时的黑色盒子 var minute = document.querySelector('.minute'); // 分钟的黑色盒子 var second = document.querySelector('.second'); // 秒数的黑色盒子 var inputTime = +new Date('2020-1-11 18:00:00'); // 返回的是用户输入时间总的毫秒数 countDown(); // 我们先调用一次这个函数,防止第一次刷新页面有空白 // 2. 开启定时器 setInterval(countDown, 1000); function countDown() { var nowTime = +new Date(); // 返回的是当前时间总的毫秒数 var times = (inputTime - nowTime) / 1000; // times是剩余时间总的秒数 var h = parseInt(times / 60 / 60 % 24); //时 h = h < 10 ? '0' + h : h; hour.innerHTML = h; // 把剩余的小时给 小时黑色盒子 var m = parseInt(times / 60 % 60); // 分 m = m < 10 ? '0' + m : m; minute.innerHTML = m; var s = parseInt(times % 60); // 当前的秒 s = s < 10 ? '0' + s : s; second.innerHTML = s; } </script> </body> </html
3、停止定时器setInterval
4、案例:发送短信倒计时
点击按钮后,该按钮60秒之内不能再次点击,防止重复发送短信。
手机号码: <input type="number"> <button>发送</button> <script> var btn = document.querySelector('button'); // 全局变量,定义剩下的秒数 var time = 3; // 定义剩下的秒数 【注意这个time的位置,写在全局没有问题】 // 注册单击事件 btn.addEventListener('click', function() { // 禁用按钮 btn.disabled = true; // 开启定时器 var timer = setInterval(function() { // 判断剩余秒数 if (time == 0) { // 清除定时器和复原按钮 clearInterval(timer); btn.disabled = false; btn.innerHTML = '发送'; } else { btn.innerHTML = '还剩下' + time + '秒'; time--; } }, 1000); }); </script>
我的写法:注意这个count的位置:(1)写在全局没有问题;(2)写在这里,则定时器函数也需要写在这里,因为定时器函数在全局,访问不了这个局部变量;(3)定时器函数写在外面,count写在外面的定时器函数里,则count每次都是3。】 手机号码: <input type="number"> <button>发送</button> <script> var btn = document.querySelector('button'); function fn() { if (count == 0) { clearInterval(timer); btn.disabled = false; btn.innerHTML = '发送'; } else { btn.disabled = true; btn.innerHTML = `剩余${count}s`; count--; } } btn.addEventListener('click', function() { var count = 3; // 【注意这个count的位置:(1)写在全局没有问题;(2)写在这里,则定时器函数也需要写在这里,否则报错,因为定时器函数在全局,访问不了这个局部变量;(3)定时器函数写在外面,count写在外面的定时器函数里,则count每次都是3。】 var timer = setInterval(fn, 1000); // var timer = setInterval(function fn() { // if (count == 0) { // clearInterval(timer); // btn.disabled = false; // btn.innerHTML = '发送'; // } else { // btn.disabled = true; // btn.innerHTML = `剩余${count}s`; // count--; // } // }, 1000); }) </script>
来源:https://www.cnblogs.com/jianjie/p/12180674.html