Skip to content

Commit 900ba7c

Browse files
committed
sprite: fix memory leak
1 parent bdb959c commit 900ba7c

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

lib/sprite.js

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ function Sprite(animationName, params) {
1818
this.rotation = params.rotation == null ? 0 : params.rotation;
1919
this.alpha = params.alpha == null ? 1 : params.alpha;
2020

21+
setUpListeners(this);
2122
this.setAnimationName(animationName);
2223
this.setLoop(params.loop);
2324
this.setVisible(params.visible == null ? true : params.visible);
@@ -177,12 +178,16 @@ Sprite.prototype.getFrameIndex = function(){
177178
};
178179

179180
Sprite.prototype['delete'] = function(){
181+
if (this.interval) this.interval();
182+
this.removeAllListeners();
180183
if (this.batch) this.batch.remove(this);
181184
this.batch = null;
182185
};
183186

184187
function setUpInterval(self) {
185-
if (self.interval) self.interval.cancel();
188+
if (self.interval) self.interval();
189+
self.interval = null;
190+
if (self.animationEndListenCount === 0) return;
186191
var _schedule = self._loop ? schedule : wait;
187192
var now = new Date();
188193
var timeSinceStart = (now - self.animationStartDate) / 1000;
@@ -194,24 +199,29 @@ function setUpInterval(self) {
194199

195200
function wait(sec, cb) {
196201
var interval = setTimeout(cb, sec * 1000);
197-
return {
198-
cancel: function(){
199-
if (interval != null) {
200-
clearTimeout(interval);
201-
interval = null;
202-
}
203-
}
202+
return function(){
203+
clearTimeout(interval);
204204
};
205205
}
206206

207207
function schedule(sec, cb) {
208208
var interval = setInterval(cb, sec * 1000);
209-
return {
210-
cancel: function(){
211-
if (interval != null) {
212-
clearInterval(interval);
213-
interval = null;
214-
}
215-
}
209+
return function(){
210+
clearInterval(interval);
216211
};
217212
}
213+
214+
function setUpListeners(self) {
215+
self.on('newListener', function(event) {
216+
if (event === 'animationend') {
217+
self.animationEndListenCount += 1;
218+
setUpInterval(self);
219+
}
220+
});
221+
self.on('removeListener', function(event) {
222+
if (event === 'animationend') {
223+
self.animationEndListenCount -= 1;
224+
setUpInterval(self);
225+
}
226+
});
227+
}

0 commit comments

Comments
 (0)