JavaScript使用setTimeout实现倒计时效果

时间:2021-05-26

为了加强对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; 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);}

执行页面

结束页面

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章