Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setInterval with CoffeeScript?

Tags:

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?

like image 839
Shamoon Avatar asked Sep 07 '11 16:09

Shamoon


People also ask

How do I run a setInterval function?

Definition and UsageThe setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

How do you run setInterval 5 times?

“setinterval for 5 times” Code Answer'svar intervalID = setInterval(alert, 1000); // Will alert every second. // clearInterval(intervalID); // Will clear the timer. setTimeout(alert, 1000); // Will alert once, after a second.

How do I make setInterval faster?

Try doing: setInterval(function () { for (var i = 0; i < 1000; i++) { // YOUR CODE } }, 10); You will actually make your code more efficient by avoiding the callback calling overhead and having longer intervals will make your code run more predictably.


1 Answers

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 
like image 163
Billy Moon Avatar answered Sep 20 '22 12:09

Billy Moon