-
-
Notifications
You must be signed in to change notification settings - Fork 843
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
IdleState - Set a idle time to wait a user answer, after this send a auto message of inactivity No have breaking changes
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
const { EventEmitter } = require('node:events') | ||
|
||
class IdleState extends EventEmitter { | ||
timer = null | ||
startTime = 0 | ||
endTime = 0 | ||
|
||
setIdleTime = (timeInSeconds) => { | ||
this.startTime = timeInSeconds | ||
return this.reset() | ||
} | ||
|
||
startTimer = () => { | ||
this.timer = setInterval(() => { | ||
const currentTime = new Date().getTime() | ||
|
||
if (currentTime > this.endTime) { | ||
this.stop() | ||
this.emit('idle') | ||
} else if (this.debug) { | ||
return this.emit('debug', () => console.info(this.debugTime())) | ||
} else { | ||
return | ||
} | ||
}, 1000) | ||
} | ||
|
||
start = () => { | ||
this.stop() | ||
if (!this.timer) { | ||
this.reset() | ||
this.startTimer() | ||
} | ||
} | ||
|
||
reset = () => { | ||
const currentTime = new Date().getTime() | ||
this.endTime = currentTime + this.startTime * 1000 | ||
} | ||
|
||
stop = () => { | ||
if (this.timer) { | ||
clearInterval(this.timer) | ||
this.timer = null | ||
} | ||
} | ||
|
||
debugTime = () => { | ||
const currentTime = new Date().getTime() | ||
return `Tiempo restante: ${((this.endTime - currentTime) / 1000).toFixed(0)} segundos` | ||
} | ||
} | ||
|
||
module.exports = IdleState |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters