毫秒倒计时小Demo

时间:2021-04-09 17:05:10

Demo截图:

毫秒倒计时小Demo

Demo:Demo

上代码:

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
</title>
<style> *{ margin:0;padding:0; } .timer{
width: 200px;
margin:0 auto;
font-family: 'Microsoft Yahei';
font-size: 18px;
line-height: 30px;
}
.timer span{
color: #ff556b;
}
.timer strong{ } </style>
<script>
window.onload = function(){ var oTimer = document.getElementById('timer'),
oBtn = document.getElementById('btn'),
oSpan = oTimer.getElementsByTagName('span')[0]; var timers = setCountdown(oSpan,10,callFn); oBtn.onclick = function(){
clearInterval( timers );
}; function callFn(){
alert( '倒计时结束了~~' );
} function setCountdown( obj,num,callBack ){
var timer = null; //定时器;
var nums = num * 1000; //时间转化成毫秒;
obj.innerHTML = num; //对象赋值; timer = setInterval(function(){ nums = nums - 100; //每次减100毫秒; if( nums <= 0 ){ callBack(); clearInterval( timer ); } obj.innerHTML = parseFloat(nums/1000).toFixed(1); },100); return timer; } }
</script>
</head>
<body>
<div id="timer" class="timer" >
<div>
<span>
</span>
<strong>

</strong>
</div>
<input type="button" id="btn" value="点我">
</div> </body>
</html>

后记:

1秒1000毫秒;

所以定时器100毫秒为间隔10次1000(1秒),每次减也是100;