Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 21771  / 9 Years ago, tue, december 15, 2015, 12:00:00

I'm trying to to add a timer for a Snake Game and to start it simultaneously when the game starts and to stop it when it's finished. Any help please? Many thanks!


More From » css

 Answers
51

The example below (just sample code) it will count 5 secs and then alert the total seconds. You need to make the math to get hours, minutes, seconds.



$(document).ready(function(){
var secs = 0;
var id = setInterval(function(){
secs++; console.log(secs);
if(secs> 5){
clearInterval(id);
alert('Total Time: ' + secs + ' seconds');
}
}, 1000);
});


Then you can put the logic inside a start/stop method or wherever you need to place it.



With pure Javascript:



window.onload = function() {
var secs = 0;
var id = setInterval(function(){
secs++; console.log(secs);
if(secs> 5){
clearInterval(id);
alert('Total Time: ' + secs + ' seconds');
}
}, 1000);
};

[#64064] Saturday, December 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tobyl

Total Points: 598
Total Questions: 110
Total Answers: 114

Location: Vietnam
Member since Sat, Feb 12, 2022
2 Years ago
tobyl questions
Tue, Aug 10, 21, 00:00, 3 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
;