Question about code in chapter 6 Clock

I’m trying to add the 3D clock on page 70, but when I put in clock, animate, and walk, I get an error:
Uncaught TypeError: Cannot read property ‘getElapsedTime’ of undefined
at walk (code.html:92)
at animate (code.html:109)

It looks like the Clock constructor isn’t working.

My whole program is here:
https://is.gd/98FTe6

Thanks for your help!

J.

The good news is that you’ve typed everything 100% correctly! The bad news… isn’t all that bad :slight_smile:

The problem is that you’ve written the animate() function 3 times. To fix, you just need to delete the first two.

The two animate() functions that need to be deleted start on line 53 and end on line 68. Delete all of that and you’ll have your avatar in the forest waving its hand!

Nice work getting this far! You would have had this perfect if it weren’t for JavaScript being weird (see below if you’re curious). It’s really just a fluke that this didn’t work – so keep going! :smile:

-Chris

The nitty gritty details (if you really want to know)…

It’s not at all surprising that you had a hard time figuring out the cause of the problem here. You’ve stumbled on a JavaScript “feature” called variable hoisting. No matter how good you get at JavaScript, this will still be hard – I get something like this every week or so.

What’s happened is that the first time the code calls the animate() function on line 58, it goes all the way down to the last animate() function body on line 105. That animate() function calls walk(), which tries to use the clock variable. You’d think that JavaScript would know what the clock variable is, since it’s defined right above walk(), but no. JavaScript knows the variable exists because it was declared, but clock is still undefined because the code has only run through animate() on line 58. The real fix is to wait to call animate() until after clock is assigned. By deleting the two animate() functions – and the two calls – the code waits until the last animate() to start walk() and using the clock. By then, the clock is defined and everything works.

Hopefully that makes some sense. It really is confusing behavior in JavaScript.

Thanks! That did the trick after I deleted the animate functions and refreshed.