Shamoon
Shamoon

Reputation: 43649

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?

Upvotes: 24

Views: 14378

Answers (1)

Billy Moon
Billy Moon

Reputation: 58619

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

Upvotes: 33

Related Questions