JavaScript计时器
<! doctype html >
< html lang = " en" > < head> < meta charset = " UTF-8" > < meta name = " viewport" content = " width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" > < meta http-equiv = " X-UA-Compatible" content = " ie=edge" > < title> JavaScript计时器</ title> < style> body { padding : 40px; margin : 0; } .timeTitle { font-size : 28px; line-height : 80px; } #timeNow { color : #67c23a; } .btn { display : inline-flex; justify-content : center; align-items : center; line-height : 1; height : 32px; white-space : nowrap; cursor : pointer; color : #FFFFFF; text-align : center; box-sizing : border-box; outline : none; transition : .1s; font-weight : 500; user-select : none; vertical-align : middle; -webkit-appearance : none; background-color : #409eff; border : 1px solid #dcdfe6; border-color : #409eff; padding : 8px 15px; font-size : 14px; border-radius : 4px; margin-right : 16px; } .btn:last-child { margin-right : 0; } .btn:hover { background-color : #79bbff; border-color : #79bbff; } .warning { background-color : #e6a23c; border-color : #e6a23c; } .warning:hover { background-color : #eebe77; border-color : #eebe77; } .danger { background-color : #f56c6c; border-color : #f56c6c; } .danger:hover { background-color : #f89898; border-color : #f89898; } </ style>
</ head> < body> < div class = " timeTitle" > 当前时间为:< span id = " timeNow" > 00:00:00</ span> </ div> < button class = " btn" id = " timeBegin" > 计时开始</ button> < button class = " btn warning " id = " timeEnd" > 计时结束</ button> < button class = " btn danger" id = " timeClear" > 计时清除</ button> < script> var timer = "" ; var beginBtn = document. getElementById ( "timeBegin" ) ; var endBtn = document. getElementById ( "timeEnd" ) ; var clearBtn = document. getElementById ( "timeClear" ) ; var beginNum = 0 ; var min, second, millisecond; min = second = millisecond = 0 ; function time ( ) { millisecond += 50 ; if ( millisecond >= 1000 ) { millisecond = 0 second += 1 ; } if ( second >= 60 ) { second = 0 min += 1 ; } counts = min + ':' + second + ':' + millisecond; document. getElementById ( "timeNow" ) . innerText = counts; } function BeginTime ( ) { beginBtn. onclick = function ( ) { if ( beginNum > 0 ) { return ; } beginNum++ ; timer = setInterval ( time, 50 ) ; } } function EndTime ( ) { endBtn. onclick = function ( ) { beginNum = 0 ; clearInterval ( timer) ; } } function ClearTime ( ) { clearBtn. onclick = function ( ) { beginNum = 0 ; clearInterval ( timer) ; document. getElementById ( "timeNow" ) . innerHTML = "00:00:00" ; } } BeginTime ( ) ; EndTime ( ) ; ClearTime ( ) </ script>
</ body> </ html>