Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created August 27, 2014 05:44
Show Gist options
  • Save ishiduca/b8faebc1c3e4225a38fa to your computer and use it in GitHub Desktop.
Save ishiduca/b8faebc1c3e4225a38fa to your computer and use it in GitHub Desktop.
Stream.Readable で インターバルタイマー
'use strict'
var stream = require('stream')
var util = require('util')
var types = {
'"timeout" must be "Number"': function (n) { return isNaN(n) }
, '"timeout" must be "Int".': function (n) { return (n + '').indexOf('.') !== -1 }
, '"timeout" must be over "0".': function (n) { return n < 0 }
}
function Timer (timeout, _opt) {
timeout = Number(timeout)
for (var p in types) {
if (types[p](timeout)) throw new TypeError(p)
}
stream.Readable.call(this, _opt)
this.timeout = timeout
this.index = 0
this.interval = 500
}
util.inherits(Timer, stream.Readable)
Timer.prototype._read = function () {
setTimeout(function () {
var i = (this.index += 1)
i > this.timeout ? this.push(null) : this.push(new Buffer(i + ''))
}.bind(this), this.interval)
}
module.exports = Timer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment