I’m using node.js and socket.io to display countdown timers. The timers are being run on node.js and emitting the times to the client via socket.io, the times are using setTimeout.
The problem is that with each connection, I’m instantiating a new prototype class that is getting the times and emitting the timers, however the times should be the same for every user. Ideally, I would use io.sockets.emit (as oppose to using the ‘socket’ callback). Then the times would be emitted to all clients (which is the desired behavior).
Right now, this would cause the timers to go nuts, since theres a new object for every client that connects.
In JavaScript, would a singleton pattern be the solution to this?
I’ve tried to use this, but didn’t seem to work:
var Auction = function() {
Auction.instance = null;
if(!Auction.instance) {
Auction.instance = this;
} else {
console.log('instance');
return Auction.instance;
}
}
Auction.prototype = {
init: function() {
//setTimeout is defined here, along with a lot of other stuff
};
}
I’m calling it doing:
var auction = new Auction;
auction.init();
This still creates the object multiple times.
Any suggestions would be great! Thank you.
This
ifclause will always pass because it follows the statement setting it tonull. You want to set it tonullonce outside the function – not each time you create an instance because that way you’re clearing the singleton each time you donew.In your case, you can just eliminate the whole
nullthing since!undefined === trueas well.