Javascript setTimout Question

Javascript setTimout Question

Postby TheCrock » 16 Nov 2020, 13:18

I am following the excellent book Foundation Game Design with HTML5 and Javascript.

I have a piece of code, which works but i'm not sure why.

function destroyAlien(alien)
//Change the alien's state and update the object
alien.state = alien.EXPLODED;


//Remove the alien after 1 second
setTimeout(removeAlien, 1000);

function removeAlien()
removeObject(alien, aliens);
removeObject(alien, sprites);

As you can see it is a function which uses setTimout to call another function. It only calls removeAlien function when it is inside the main function. If I move callAlien function out of the main function it does not work. I am puzzled as to why this is.

Can any sage member here tell me why this is?
Thanks in advance
Posts: 3
Joined: 12 Nov 2020, 16:02

Re: Javascript setTimout Question

Postby mdtrooper » 23 Nov 2020, 00:05

Did you fixed the code? Because your post is from some days ago.

Well, do you have this code in any code repository? Because I don't know what it is the reason to fail when the function is out.
And I have a Patreon in
User avatar
Posts: 169
Joined: 26 Jul 2012, 13:24
Location: Spain

Re: Javascript setTimout Question

Postby TheCrock » 30 Nov 2020, 00:28

Hi midtroop. Because i created the variable alien inside the function it is a temporary variable. It could not access the alien variable in the main program. Making a variable within the function ties the variable's scope to within the function. If i understand it correctly.

thanks for your reply and interest.
Posts: 3
Joined: 12 Nov 2020, 16:02

Who is online

Users browsing this forum: No registered users and 1 guest