Note that there are some explanatory texts on larger screens.

plurals
  1. POnode.js recursive setTimeout() inside of a psuedoclass
    text
    copied!<p>I think I'm having a difficult time wrapping my head around the scope of the following code:</p> <pre><code>var EventEmitter = require('events').EventEmitter, util = require('util'); // Here is the Ticker constructor: var Ticker = function(time) { this.time = time; this.tick = function() { this.emit('tick'); setTimeout(this.tick(), this.time); }; } util.inherits(Ticker, EventEmitter); var newTicker = new Ticker(1000); newTicker.on('tick', function() { console.log("TICK"); }); newTicker.tick(); </code></pre> <p>What ends up happening, is that the "tick" gets called many, many times filling up the stack without the setTimeout actually setting the timeout to one second.</p> <p>Could any explain to me what's going on?</p> <hr> <p><strong>EDIT:</strong> I looked a little bit more, and I still couldn't figure out the issue of scope, really.</p> <p>What I ended up doing was following the solution that was given for the problem, which I tried to solve by way of setTimeout().</p> <p>The solution given was:</p> <pre><code>var EventEmitter = require('events').EventEmitter, util = require('util'); // Here is the Ticker constructor: var Ticker = function(time) { var self = this; this.time = time; setInterval(function() { self.emit('tick'); }, self.time); }; util.inherits(Ticker, EventEmitter); var ticker = new Ticker(1000); ticker.on('tick', function() { console.log("TICK"); }); </code></pre> <p>It does make more sense to me... What I'm wondering now is: Do inner functions and objects in javascript not keep track of their parent's scope and variables?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload