javascript 如何使用 CoffeeScript 设置间隔?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7337648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:45:51  来源:igfitidea点击:

How do I setInterval with CoffeeScript?

javascriptcoffeescript

提问by Shamoon

My JavaScript is as follows:

我的 JavaScript 如下:

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?

什么是等效的 CoffeeScript?

回答by Billy Moon

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 notreturning the setInterval.

它也返回 true 而不是 setInterval,虽然我个人看不出返回 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.

这是一个带有粗箭头(见评论)和解构赋值(见其他评论)的版本。此外,返回 setInterval 而不是显式返回 true。

util = require 'util'

{EventEmitter} = require 'events'

Ticker = ->
  setInterval =>
    @emit 'tick'
  , 1000