JSFiddle - React, Tailwind, and code Playground
HTML
<div id="timer">
<span id="tiktock">5:00</span><br>
<button id="btn">开始倒计时</button>
</div>
CSS
#timer{
width: 100%;
margin: 30px auto;
text-align: center;
font-size: 18px;
}
#btn{
margin-top:20px;
width: 120px;
height: 48px;
background-color: #4679BD;
color: #fff;
border: 0;
font-size: 16px;
outline: none;
cursor: pointer;
}
JavaScript
var total = 500;
var timer = null;
var tiktock = document.getElementById('tiktock');
var btn = document.getElementById('btn');
function countdown(){
timer = setInterval(function(){
total--;
if (total<=0) {
clearInterval(timer);
tiktock.innerHTML= "0:00";
}else{
var ss = Math.floor(total/100);
var ms = total-Math.floor(total/100)*100;
tiktock.innerHTML=ss + ":" + ms;
}
},10);
};
btn.addEventListener('click', countdown, false);