LoginSignup
7
7

More than 5 years have passed since last update.

setTimeoutくんとsetIntervalさんの引数と仲良くなれなれませんでした

Last updated at Posted at 2014-06-13

ということで

class after
  constructor: (time) ->
    return new after(time) unless this instanceof after
    @time = time
  using: ->
    (@args = Array::slice.call(arguments)) and @
  run: (callback) ->
    if @args?
      @args.unshift(callback, @time)
      setTimeout.apply(null, @args)
    else
      setTimeout(callback, @time)

class eachTime
  constructor: (time) ->
    return new eachTime(time) unless this instanceof eachTime
    @time = time
  using: ->
    (@args = Array::slice.call(arguments)) and @
  run: (callback) ->
    if @args?
      @args.unshift(callback, @time)
      setInterval.apply(null, @args)
    else
      setInterval(callback, @time)
after(300).run ->
  # do something

after(500).using('hoge', 'fuga').run(callback_having_two_args)

eachTime(100).run ->
  # do something

eachTime(50).using('foo', 'bar').run(callback_having_two_args)

JS版

var after, eachTime;

after = (function() {
  function after(time) {
    if (!(this instanceof after)) {
      return new after(time);
    }
    this.time = time;
  }

  after.prototype.using = function() {
    this.args = Array.prototype.slice.call(arguments)
    return this;
  };

  after.prototype.run = function(callback) {
    if (this.args != null) {
      this.args.unshift(callback, this.time);
      return setTimeout.apply(null, this.args);
    } else {
      return setTimeout(callback, this.time);
    }
  };

  return after;
})();

eachTime = (function() {
  function eachTime(time) {
    if (!(this instanceof eachTime)) {
      return new eachTime(time);
    }
    this.time = time;
  }

  eachTime.prototype.using = function() {
    this.args = Array.prototype.slice.call(arguments)
    return this;
  };

  eachTime.prototype.run = function(callback) {
    if (this.args != null) {
      this.args.unshift(callback, this.time);
      return setInterval.apply(null, this.args);
    } else {
      return setInterval(callback, this.time);
    }
  };

  return eachTime;
})();
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7