3.2 停止定时器clearTimerout()
<!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> </head> <body> <button>点击停止定时器</button> <script> var btn = document.querySelector('button'); var timer = setTimeout(function() { console.log('爆炸了'); }, 5000); btn.addEventListener('click', function() { clearTimeout(timer); }) </script> </body> </html>
<!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('2021-9-6 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
<!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> </head> <body> <button>点击</button> <div></div> <script> var btn = document.querySelector('button'); var div = document.querySelector('div'); var timer = 5; btn.addEventListener('click', function() { setInterval(function() { if (timer == 0) { location.href = 'http://www.baidu.com'; } else { div.innerHTML = '您将在' + timer + '秒钟之后跳转到首页'; timer--; } },1000); }) </script> </body> </html>