+ 2

Javascript Timer (simplegame.js)

Currently Im reading the Book: HTML5 game development for dummies and there is a exercise for a timer. <!DOCTYPE html> <html> <head> <title>timerDemo</title> <script type="text/javascript" src="simpleGame.js"></script> <script type="text/javascript"> var timer; var output; var game; function init() { game = new Scene(); output = document.getElementById("output"); timer = new Timer(); timer.reset(); game.start(); } function update() { game.hide(); currentTime = timer.getElapsedTime(); output.innerHTML = currentTime; } function reset() { timer.reset(); } </script> </head> <body onload="init()"> <div id="output">empty</div> <button onclick = "reset()">reset timer</button> </body> </html> I want to add an additional variable var maxTime = 5 sec and a if function that check if the currentTime is equal to maxTime if this is ture the timer should be reset to zero but i can't figure out, where i have to write this if-statement <!DOCTYPE html> <html> <head> <title>timerDemo</title> <script type="text/javascript" src="simpleGame.js"></script> <script type="text/javascript"> var timer; var output; var game; var maxTime; function init() { game = new Scene(); output = document.getElementById("output"); timer = new Timer(); timer.reset(); game.start(); maxTime = new Timer(); maxTime = 5; } function update() { game.hide(); currentTime = timer.getElapsedTime(); output.innerHTML = currentTime; console.log(maxTime); console.log(currentTime); } function reset() { timer.reset(); } </script> </head> <body onload="init()"> <div id="output">empty</div> <button onclick = "reset()">reset timer</button> </body> </html>

18th Aug 2018, 1:27 PM
Maxim Schiffmann
Maxim Schiffmann - avatar
2 Answers
+ 4
Put it in the update function
18th Aug 2018, 2:10 PM
qwerty
qwerty - avatar
+ 4
I figured it out now :) <!DOCTYPE html> <html> <head> <title>timerDemo</title> <script type="text/javascript" src="simpleGame.js"></script> <script type="text/javascript"> var timer; var output; var game; var cTime; var maxTime; function init() { game = new Scene(); output = document.getElementById("output"); timer = new Timer(); timer.reset(); game.start(); maxTime = new Timer(); maxTime = 5; } function update() { game.hide(); currentTime = timer.getElapsedTime(); output.innerHTML = currentTime; console.log(maxTime); console.log(currentTime); checkTime(); } function reset() { timer.reset(); } function checkTime() { cTime = timer.getElapsedTime(); if (cTime > maxTime) { reset(); } } </script> </head> <body onload="init()"> <div id="output">empty</div> <button onclick = "reset()">reset timer</button> </body> </html>
18th Aug 2018, 3:59 PM
Maxim Schiffmann
Maxim Schiffmann - avatar