Jump to content

Beginner to JavaScript, having trouble with variable :(

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 post
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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...