-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebSocketTimer.js
More file actions
87 lines (69 loc) · 1.91 KB
/
Copy pathwebSocketTimer.js
File metadata and controls
87 lines (69 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var util = require('util')
/**
* The timer is intended for a multiplayer game where you want to limit how much time a person has to submit their command
*/
function WebSocketTimer(options){
options = options || {}
var defaults={
startTime:0,
stopTime:0,
increment:1,
endFunc:null
}
util._extend(defaults, options)
util._extend(this, defaults)
//extends the defaults
this.curTime = this.startTime
this.frequency= 1000 //send the time every second
this.webSocket = null
this.timerHandle = null
this.curPlayer = null
}
//allow to change the settings midway through
WebSocketTimer.prototype.changeSettings(options){
util._extend(this, options)
}
WebSocketTimer.prototype.addWebSocket = function(webSocket){
this.webSocket = webSocket
var that = this
webSocket.on('close', function(){
console.log('stopping the timer')
that.stop()
})
}
WebSocketTimer.prototype.reset = function(webSocket, currentPlayer){
this.curTime = this.startTime
this.curPlayer = currentPlayer
this.addWebSocket(webSocket)
}
WebSocketTimer.prototype.start = function(){
var that = this
this.timerHandle = setInterval( function(){
that.callback.call(that)
} , this.frequency)
}
WebSocketTimer.prototype.stop = function(){
clearInterval(this.timerHandle)
}
WebSocketTimer.prototype.callback = function(){
this.curTime += this.increment
console.log(this.curTime)
if(this.webSocket){
//allow to send to a group of websockets too
if(Object.prototype.toString.call( this.webSocket ) === '[object Array]'){
for(var i=0; i<this.webSocket.length; i++){
this.webSocket[i].send(JSON.stringify({timer:this.curTime}))
}
}else{
this.webSocket.send(JSON.stringify({timer:this.curTime}))
}
}
if(this.curTime == this.stopTime){
if(this.endFunc){
this.endFunc()
}
this.stop()
}
}
WebSocketTimer
module.exports = WebSocketTimer