How do I setInterval with CoffeeScript?
My JavaScript is as follows:
var util = require('util');
EventEmitter = require('events').EventEmitter;
var Ticker = 开发者_如何学运维function() {
var self = this;
setInterval( function() {
self.emit('tick');
}, 1000 );
}
What's the equivalent CoffeeScript?
util = require 'util'
EventEmitter = require('events').EventEmitter
Ticker = ->
self = this
setInterval ->
self.emit 'tick'
, 1000
true
You add the second parameter by lining up the comma with the function you are passing to, so it knows a second parameter is coming.
It also returns true instead of setInterval, although I can't personally see the advantage of not returning the setInterval.
Here is a version with thick arrow (see comments), and destructuring assignment (see other comment). Also, returning the setInterval instead of explicitly returning true.
util = require 'util'
{EventEmitter} = require 'events'
Ticker = ->
setInterval =>
@emit 'tick'
, 1000
精彩评论