From 53377897721e2e7a16572a53bfd33048e7f474a9 Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Sun, 20 Sep 2015 00:48:07 +0100 Subject: [PATCH] Fix election timeout bug and tidy up fixes #34 --- lib/gather/gather.js | 44 ++++++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/lib/gather/gather.js b/lib/gather/gather.js index a117117..ba99e22 100644 --- a/lib/gather/gather.js +++ b/lib/gather/gather.js @@ -25,9 +25,12 @@ function Gather (options) { options.onEvent : noop; this.TEAM_SIZE = 6; this.gatherers = []; - this.ELECTION_INTERVAL = 120000; // 2 mins this.REGATHER_THRESHOLD = 6; - this.electionStartTime = null; + this.election = { + INTERVAL: 120000, // 2 mins + startTime: null, + timer: null + }; this.initState(); } @@ -70,17 +73,11 @@ StateMachine.create({ onenterelection: () => { // Setup timer for elections - let self = this; - self.electionStartTime = new Date(); - setTimeout(() => { - if (self.can("electionTimeout")) { - self.electionTimeout(); - } - }, self.ELECTION_INTERVAL); + this.startElectionCountdown(); }, onleaveelection: () => { - this.electionStartTime = null; + this.cancelElectionCountdown(); }, // Selection State @@ -282,9 +279,9 @@ Gather.prototype.marines = () => { return this.retrieveGroup("marine"); }; -Gather.prototype.electionTimer = () => { - return (this.electionStartTime === null) ? - null : this.electionStartTime.toISOString(); +Gather.prototype.electionStartTime = () => { + return (this.election.startTime === null) ? + null : this.election.startTime.toISOString(); }; Gather.prototype.toJson = () => { @@ -293,8 +290,8 @@ Gather.prototype.toJson = () => { state: this.current, pickingTurn: this.pickingTurn(), election: { - startTime: this.electionTimer(), - interval: this.ELECTION_INTERVAL + startTime: this.electionStartTime(), + interval: this.election.INTERVAL } } }; @@ -332,6 +329,21 @@ Gather.prototype.regatherVotes = () => { if (gatherer.regatherVote) acc++; return acc; }, 0); -} +}; + +// Initiates a timer which will push gather into next state +Gather.prototype.startElectionCountdown = () => { + let self = this; + self.election.startTime = new Date(); + this.election.timer = setTimeout(() => { + if (self.can("electionTimeout")) self.electionTimeout(); + }, self.election.INTERVAL); +}; + +Gather.prototype.cancelElectionCountdown = () => { + clearInterval(this.election.timer); + this.election.timer = null; + this.election.startTime = null; +}; module.exports = Gather;