Calculate time between 2 events in Javascript -
i'm doing beginners course in javascript , working on basic project reaction timer. idea random shapes (squares or circles only) appear in random positions @ random intervals , user has click on them.
here's have far:
document.addeventlistener("domcontentloaded", function() { var shape = document.getelementbyid("shape"); function generaterandomshape() { console.log("test"); var shapetype = ["50%", ""]; var shapecolor = ["red", "green", "yellow", "purple", "orange", "brown", "gray", "black", "blue"]; shape.classlist.remove("disappear"); shape.style.backgroundcolor = shapecolor[math.floor(math.random() * shapecolor.length)]; shape.style.height = math.random() * 300 + "px"; shape.style.width = shape.style.height; shape.style.borderradius = shapetype[math.floor(math.random() * shapetype.length)]; shape.style.marginleft = math.random() * 700; shape.style.margintop = math.random() * 300; } shape.onclick = function() { var endtime = date.now(); var randomdelay = math.random() * 3000; var starttime = endtime - randomdelay; var reaction = (endtime - starttime) / 1000; settimeout(generaterandomshape, randomdelay); shape.classname = "disappear"; document.getelementbyid("end").innerhtml = endtime; document.getelementbyid("start").innerhtml = starttime; document.getelementbyid("reactiontime").innerhtml = reaction; } generaterandomshape(); });
.disappear { display: none; }
<h1>test reactions!</h1> <p>click on boxes , circles can!</p> <p>your time is: <span id="reactiontime"></span> seconds</p> <div id="shape"></div> <div id="start"></div> <div id="end"></div> <div id="reactiontime"></div>
it works ok except reaction timer , cannot work out how work. i'm creating endtime variable upon clicking shape cannot head around starttime variable. how store time shape appeared? attempt here doesn't work , can see why, cannot figure out should putting. appreciated!
have generate shape , shape event listener in same scope.
in same scope, create 2 variables track showtime
, , clicktime
... set showtime
when generate random shape, set click time inside event listener, populate html.
var showtime, clicktime; function generateshape() { showtime = date.now(); ... } ... shape.onclick = function() { clicktime = date.now(); document.getelementbyid('reactiontime').innerhtml = clicktime - showtime; ... }
wiki
Comments
Post a Comment