Last active
June 14, 2017 18:45
-
-
Save hoffination/3581c189efd53536dcaec52b47587dd1 to your computer and use it in GitHub Desktop.
'this' within a prototype offers improvements over the previous microwave example
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
(function() { | |
"use strict" | |
function Microwave() { | |
this.timer = null | |
this.eventListener = null | |
} | |
Microwave.prototype.start = function(timeMS, callback) { | |
this.eventListener = callback | |
this.timer = setTimeout((() => { | |
this.timer = null | |
this.eventListener('done') | |
}).bind(this), timeMS) | |
} | |
Microwave.prototype.stop = function() { | |
if (this.timer) { | |
clearTimeout(this.timer) | |
this.timer = null | |
this.eventListener = null | |
return true | |
} else { | |
return false | |
} | |
} | |
Microwave.prototype.isRunning = function() { | |
return !!this.timer; | |
} | |
let microwave = new Microwave(); | |
let micro2 = new Microwave(); | |
microwave.start(10000, console.log) | |
console.log(microwave.isRunning()) // true | |
console.log(micro2.isRunning()) // false | |
console.log("stopped: ", microwave.stop()) // stopped: true | |
console.log(microwave.isRunning()) // false | |
microwave.start(100, console.log) // .... done | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment