How to implement HTML5 timer
This article mainly explains "how to achieve HTML5 timer". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to achieve HTML5 timer.
Html:
The code is as follows:
HTML5 Timer for work-relax balance
CountDownSeconds = 60
Var handle = null
/ / window load
Function onLoadWindow () {
ACanvas = document.getElementById ("countdownCanvas")
Context = aCanvas.getContext ("2d")
Var canvasText = "Press to Start..."
Var xPos = aCanvas.width / 2
Var yPos = aCanvas.height / 2
Context.font = "12pt Century Gothic"
Context.fillStyle = "# 008000;"
Context.textAlign = "center"
Context.textBaseline = "middle"
Context.fillText (canvasText, xPos, yPos)
}
Function updateCanvas (theContext, width, height) {
If (countDownSeconds < 0) {
ClearInterval (handle)
Handle = null
Alert ("hey, time is up!")
Return 0
}
MinStr = Math.floor (countDownSeconds / 60)
SecStr = countDownSeconds 60
If (minStr < 10) {
MinStr = "0" + minStr
}
If (secStr < 10) {
SecStr = "0" + secStr
}
Context.clearRect (0,0, width, height)
Context.font = "24pt Century Gothic"
Context.fillText (minStr + ":" + secStr, width / 2, height / 2)
CountDownSeconds--
}
Function startWorkCountDown () {
If (handle! = null) {
ClearInterval (handle)
}
CountDownSeconds = document.getElementById ("workIntervalInput") .value * 60
TimeDisplayCanvas = document.getElementById ("countdownCanvas")
TimeDisplayContext2D = timeDisplayCanvas.getContext ("2d")
UpdateCanvas (timeDisplayContext2D, timeDisplayCanvas.width, timeDisplayCanvas.height)
Handle = setInterval (function () {
UpdateCanvas (timeDisplayContext2D, timeDisplayCanvas.width, timeDisplayCanvas.height)
}, 1000)
}
Function startRestCountDown () {
If (handle! = null) {
ClearInterval (handle)
}
CountDownSeconds = document.getElementById ("restIntervalInput") .value * 60
TimeDisplayCanvas = document.getElementById ("countdownCanvas")
TimeDisplayContext2D = timeDisplayCanvas.getContext ("2d")
UpdateCanvas (timeDisplayContext2D, timeDisplayCanvas.width, timeDisplayCanvas.height)
Handle = setInterval (function () {
UpdateCanvas (timeDisplayContext2D, timeDisplayCanvas.width, timeDisplayCanvas.height)
}, 1000)
}
Work Hard