PunyOne Posted May 25, 2014 Share Posted May 25, 2014 I have problem with timer - I want a repeated execution of a function, which works if the function is lambda, but not if the function has a name.For illustration, this code writes the console every second:game.module('game.main') .body(function() { SceneGame = game.Scene.extend({ init: function() { this.addTimer(1000, function() { console.log('second'); }, true); } }); game.start(); });This code writes the console exactly once, after a second:game.module('game.main') .body(function() { SceneGame = game.Scene.extend({ init: function() { this.addTimer(1000, this.my_timer(), true); }, my_timer: function() { console.log('second'); } }); game.start(); });In my understanding they should be equal, but I have subpar knowledge of JS, so maybe it's some scoping thing? Quote Link to comment Share on other sites More sharing options...
enpu Posted May 25, 2014 Share Posted May 25, 2014 You should use bind.init: function() { this.addTimer(1000, this.my_timer.bind(this), true);} nacs and PunyOne 2 Quote Link to comment Share on other sites More sharing options...
PunyOne Posted May 25, 2014 Author Share Posted May 25, 2014 You should use bind.init: function() { this.addTimer(1000, this.my_timer.bind(this), true);}Thank you!I Googled a bit based on your reference and now I also understand that I was passing a result of calling 'my_timer()' rather than the function itself.For the completeness, this would also work, but 'SceneGame' would not be accessible from within of 'my_timer':game.module('game.main') .body(function() { SceneGame = game.Scene.extend({ init: function() { this.addTimer(1000, this.my_timer, true); }, my_timer: function() { console.log('second'); } }); game.start(); }); Quote Link to comment Share on other sites More sharing options...
PunyOne Posted May 28, 2014 Author Share Posted May 28, 2014 Following on the previous - I found that the timers keep running after the change of scene, meaning that:game.module('game.main') .body(function() { SceneGame = game.Scene.extend({ init: function() { this.addTimer(1000, this.my_timer, true); game.system.setScene(End); }, my_timer: function() { console.log('second'); this; } }); game.start(); End = game.Scene.extend({ init: function() {} }); });will still call the timer every second, even though the scene have changed (and will crash if I put breakpoint in the timer). I figured that I can just set this.timers = []; before the scene change, however that does not feel nice. Any suggested approach? Quote Link to comment Share on other sites More sharing options...
enpu Posted May 28, 2014 Share Posted May 28, 2014 You should not change scene on scene's init function. PunyOne 1 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.