Skip to content

Instantly share code, notes, and snippets.

@hoffination
Last active June 14, 2017 18:45
Show Gist options
  • Save hoffination/3581c189efd53536dcaec52b47587dd1 to your computer and use it in GitHub Desktop.
Save hoffination/3581c189efd53536dcaec52b47587dd1 to your computer and use it in GitHub Desktop.
'this' within a prototype offers improvements over the previous microwave example
(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