javascript - Jquery: setTimeout Timer and Corresponding High Score List Do Not Match -
this seems simple problem, can't seem find posts similar issue. i've written basic timer in jquery , starts , stops click of 2 buttons, , time @ stops passed high score list appears after. appears on high score list 0.01 seconds lower number on timer. there settimeout method cause this, or missing something?
fiddle here: https://jsfiddle.net/nbsteuv/j9otp5ya/
here's code i'm using timer:
function timer(){ if(starttimer=="true"){ settimeout(function(){ i=i+0.01; $(".timer").html("<h1><center>"+ i.tofixed(2) + "</center></h1>"); timer(); },10); }; };
and here's code updates high score list:
$(".stopbutton").click(function(){ if(starttimer== "true"){ starttimer= "false"; updatescores(i); darken(".space"); }; }); function updatescores(newscore){ if(newscore > highscore1){ var redscore="score1"; highscore5=highscore4; highscore4=highscore3; highscore3=highscore2; highscore2=highscore1; highscore1=newscore; }else if(newscore > highscore2){ var redscore="score2"; highscore5=highscore4; highscore4=highscore3; highscore3=highscore2; highscore2=newscore; }else if(newscore > highscore3){ var redscore="score3"; highscore5=highscore4; highscore4=highscore3; highscore3=newscore; }else if(newscore > highscore4){ var redscore="score4"; highscore5=highscore4; highscore4=newscore; }else if(newscore > highscore5){ var redscore="score5"; highscore5=newscore; }; var highscoreplace1= "<div class='score' id='score1'><h1><center>" + highscore1.tofixed(2) + "</center></h1></div>"; var highscoreplace2= "<div class='score' id='score2'><h1><center>" + highscore2.tofixed(2) + "</center></h1></div>"; var highscoreplace3= "<div class='score' id='score3'><h1><center>" + highscore3.tofixed(2) + "</center></h1></div>"; var highscoreplace4= "<div class='score' id='score4'><h1><center>" + highscore4.tofixed(2) + "</center></h1></div>"; var highscoreplace5= "<div class='score' id='score5'><h1><center>" + highscore5.tofixed(2) + "</center></h1></div>"; $("#highscores").append(highscoreplace1, highscoreplace2, highscoreplace3, highscoreplace4, highscoreplace5, resetbutton); $("#highscores").slidedown(1000); $("#"+redscore).css("color", "red"); $(".resetbutton").click(function(){ gamereset(); }); };
full code, including variables , other functions, in fiddle.
it looks when click stop button, timer runs 1 more time, value of 'i' set value had when clicked (0.01 less). add 0.01 in click event stop button, updatescores(i+0.01);
or perhaps find better way of doing altogether :). take @ satckoverflow answer: how create stopwatch using javascript?
Comments
Post a Comment