Impact

This forum is read only and just serves as an archive. If you have any questions, please post them on github.com/phoboslab/impact

1 decade ago by FabienM

Hi,
I have a game with several levels.
One of my entity has a timer in it ( with the javascript function setTimeout)
When I load my second level, I can always see the logs from level 1's entities
So I looked into the "loadlevel" function , and it appears that the javascript objects are not destroyed, just erased form the "entites" array.

Is that normal to keep all the javascript objects ?
How can I do with my timer ?

thx
Fabien

1 decade ago by FabienM

Re
I use the ig.timer class now and it's better
No object is interacting anymore

1 decade ago by dominic

This is a good example why Impact specifically avoids using callbacks: it gets very hard to reason about code that uses a lot of callbacks - especially in games. Long explanation follows:

It's a restriction of JavaScript. You can't "destroy" objects, you can only delete references to them. Then, every once in a while, the Browser's Garbage Collector runs, figures out which objects don't have any references to them and deletes them.

So if an Entity is removed from the entities array and no other references are saved anywhere, the Entity will eventually be deleted. Note though, that as soon the Entity is removed from the array, it is no longer updated or drawn - as far as Impact is concerned, it doesn't exist anymore, but it still occupies a bit of memory.

Now, if you do something like this in your Entity:
init: function( x, y, settings ) {
	this.parent( x, y, settings );
	
	setInterval( this.doSomething.bind(this), 1000 );
},

doSomething: function() {
	ig.log('Doing something!');
}

The .bind(this) will create a closure around your entity. The this is saved inside the closure function. In turn, the closure function is saved by the JavaScript engine, because it&039;s still needed by #setInterval(). So the Entity will never be deleted, as long as setInterval() still holds a reference to the closure. You&039;d have to explicitly clear the interval/timeout in the Entity's #kill() method.

However, you already figured out the "best practice" way to avoid things like this in Impact: use ig.Timer.

1 decade ago by FabienM

Clear explanation

thanks :)
Fabien
Page 1 of 1
« first « previous next › last »