-1
    <script>
        var start;
        function shapeAppear() {
            document.getElementById("shapes").style.display = "block";
            var start = new Date().getTime();           

        }
        function delay() {
            setTimeout(shapeAppear,Math.random() *2000);
        }
        delay();

    document.getElementById("shapes").onclick = function() {
    document.getElementById("shapes").style.display = "none";   
    var position = Math.floor(Math.random() * 500);
    document.getElementById("shapes").style.left = position + "px";
    document.getElementById("shapes").style.right = position + "px";
    document.getElementById("shapes").style.top = position + "px";
    document.getElementById("shapes").style.bottom = position + "px";
    var end = new Date().getTime();
    var time =  end - start;
    time /= 1000;
    document.getElementById("time").innerHTML = time + "s";
    delay();
}   
    </script>

Here in this code i want the date() function to return a specific integer value. Because when we subtract the two Date() functions we must get the integer value.

Kunal Raut
  • 2,495
  • 2
  • 9
  • 25
  • 1
    Honestly, I don't understand your question, but it looks like you're trying to calculate the time required to do some operation... if this is your use case, I'd take a look at https://stackoverflow.com/questions/313893/how-to-measure-time-taken-by-a-function-to-execute – Jordi Nebot Apr 02 '20 at 09:35
  • Looks to me like start is used before it is set. – Rodney Apr 02 '20 at 09:36
  • You never assign a value to the `start` variable declared on line one. Only to the `start` variable declared on line 4, which uses `var` so is a **different** variable which is assigned a value that is never read because it immediately drops out of scope. – Quentin Apr 02 '20 at 09:37

1 Answers1

3

It is a scoping issue. if you use var inside a function, that variable will only exist in the scope of that function.

So what you could do is this:

var start;

function shapeAppear() {
    start = new Date().getTime();
}

By removing var in the shapeAppear function, you're updating the var that is created outside the function.

Besides that as Rodney mentioned you call delay before shapeAppear which means that start is not defined when calling delay.

Hope that makes sense.

Evert vd H.
  • 343
  • 1
  • 8
  • 1
    Yeah but also shapeAppear isn't called until after start is used, so start is still used before it is set. – Rodney Apr 02 '20 at 09:37
  • In this case it should be _"...that variable will **also** exist in the scope of that function..."_. Both `start` variables exist but the inner "masks" the outer one – Andreas Apr 02 '20 at 09:38