Jump to content

Beginner to JavaScript, having trouble with variable :(


Uzair3D

Recommended Posts

Please look at the code:

in this line: line#42reactionTime = (clickedTime - startTime)/1000;

all browsers are saying that startTime is not defined :/

any help will be appreciated :good:

<!doctype html><html><head>    <title>Learning JavaScript</title>    <meta charset="utf-8" />    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <meta name="viewport" content="width=device-width, initial-scale=1" />                  <style type = "text/css">        #simpleBox{        width:200px;        height:200px;        background-color:red;        display:none;    }            </style></head><body>    <div id = "simpleBox"></div>    <script type = "text/javascript">                function makeBox() {         var clickedTime;         var startTime;         var reactionTime;            var x = Math.random();                x = x*5000;                                setTimeout(function (){                    document.getElementById("simpleBox").style.display = "block";                    startTime = Date.now();                }, x);        }        document.getElementById("simpleBox").onclick = function (){            clickedTime = Date.now();            reactionTime = (clickedTime - startTime)/1000;            alert(reactionTime);            this.style.display = "none";            makeBox();        }        makeBox();            </script></body></html>
Edited by Uzair3D
Link to comment
Share on other sites

Try removing var startTime out of the function makeBox and have it right before the makeBox function. Because it's in makeBox, the scope for that variable is local to the makeBox function only.

  • Like 1
Link to comment
Share on other sites

Try removing var startTime out of the function makeBox and have it right before the makeBox function. Because it's in makeBox, the scope for that variable is local to the makeBox function only.

You are awesome. Thanks :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...