JavaScript使用setTimeout实现倒计时效果
为了加强对JavaScript原生代码的编写能力,以及巩固setTimeout()的使用方法,制作了一个倒计时的demo,倒计时在现在的网站中算是一个常见的小功能,如果大家喜欢的话可以留下,就当作一个日常实用的小脚本。
实现思路
1、先获取小时值 将小时值减1开始进行倒计时 分钟59 秒数59
2、秒数的个位从9开始递减,当秒数个位小于0时,秒数的十位减1
3、秒数的十位小于0时,分钟的个位减1
4、分钟的个位小于0时,分钟的十位减1
5、分钟的十位小于0时,小时减1
6、小时数小于0后停止计时全部为0
实现代码
html
<p>倒计时:</p> <span id="hour">5</span> <span>:</span> <span id="minuteTen">0</span> <span id="minuteBit">0</span> <span>:</span> <span id="secondTen">0</span> <span id="secondBit">0</span>
css
span{ display: inline-block; width: 20px; height: 20px; background-color: #000000; color: #ffffff; text-align: center; }
JavaScript
function time(){ /*小时*/ var hourTxt = document.getElementById("hour"); var hour = parseInt(document.getElementById("hour").innerHTML); /*分钟*/ var minuteTenTxt = document.getElementById("minuteTen"); var minuteBitTxt = document.getElementById("minuteBit"); var minuteTen = parseInt(document.getElementById("minuteTen").innerHTML); var minuteBit = parseInt(document.getElementById("minuteBit").innerHTML); /*秒*/ var secondTenTxt = document.getElementById("secondTen"); var secondBitTxt = document.getElementById("secondBit"); var secondTen = parseInt(document.getElementById("secondTen").innerHTML); var secondBit = parseInt(document.getElementById("secondBit").innerHTML); function start(){ hour--; hourTxt.innerHTML = hour; minuteTen = 5; minuteTenTxt.innerHTML = minuteTen; minuteBit = 9; minuteBitTxt.innerHTML = minuteBit; secondTen = 5; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; /*secondBit开始自减*/ function second(){ secondBit--; secondBitTxt.innerHTML = secondBit; /*十秒过后*/ if(secondBit < 0){ secondTen--; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; /*继续倒计时*/ setTimeout(second,1000); /*一分钟过后*/ if(secondTen < 0){ minuteBit--; minuteBitTxt.innerHTML = minuteBit; secondTen = 5; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; /*十分钟过后*/ if(minuteBit < 0){ minuteTen--; minuteTenTxt.innerHTML = minuteTen; minuteBit = 9; minuteBitTxt.innerHTML = minuteBit; } /*一个小时过后*/ if(minuteTen < 0){ hour--; hourTxt.innerHTML = hour; minuteTen = 5; minuteTenTxt.innerHTML = minuteTen; minuteBit = 9; minuteBitTxt.innerHTML = minuteBit; secondTen = 5; secondTenTxt.innerHTML = secondTen; secondBit = 9; secondBitTxt.innerHTML = secondBit; } /*倒计时结束*/ if(hour < 0 ){ hour = 0; hourTxt.innerHTML = hour; minuteTen = 0; minuteTenTxt.innerHTML = minuteTen; minuteBit = 0; minuteBitTxt.innerHTML = minuteBit; secondTen = 0; secondTenTxt.innerHTML = secondTen; secondBit = 0; secondBitTxt.innerHTML = secondBit; clearTimeout(second); clearTimeout(start); } } }else{ setTimeout(second,1000); } } setTimeout(second,1000); } setTimeout(start,1000); }
执行页面
结束页面
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)