urish / angular-moment

Moment.JS directives for Angular.JS (timeago and more)
MIT License
2.6k stars 397 forks source link

Let duration be passed to $timeout and $interval #247

Closed jrencz closed 8 years ago

jrencz commented 8 years ago

I just came with a conclusion that if I'm using moment in my project then it's redundant to write:

$timeout(someFunction, moment.duration(2, 's').asMilliseconds())

each time we pass a duration (conceptual) using Duration (as in moment.isDuration(duration) === true)

I'm about to write 2 simple decorators for both $interval and $timeout to allow passing Duration instead of number of milliseconds like this:

$timeout(someFunction, moment.duration(2, 's')))

Do you think it fits into a concept of "angular-moment" (as in "a module to integrate moment in an angular app)?

jrencz commented 8 years ago

note to self: it would be nice to be able to patch $timeout.flush and $interval.flush test helpers as well. This might not actually fit here out of the box

urish commented 8 years ago

@jrencz I believe that patching $timeout and $interval is not the right way to go.

We can either provide amTimeout and amInterval services, that provide this functionality (e.g. amTimeout(callback, 5, 's')) or just create these methods in the amMoment service

jrencz commented 8 years ago

In my opinion there's no point in doing that. The point is to reduce number of services one has to remember of, not add another 1 or 2.

jrencz commented 8 years ago

@urish since Duration object has valueOf implemented and it returns number of milliseconds and angular passes the delay argument directly to browser's setTimeout which calls valueOf internally (for that one I haven't found a source actually so it has to be checked if all browsers behave this way).

So it's probable that it's save to pass a duration directly to $timeout and $interval

jrencz commented 8 years ago

Ok, I've got a quote for the last part:

http://www.w3.org/TR/2011/WD-html5-20110525/timers.html#timers

When the above methods are to get the timeout, they must run the following steps:

  1. Let timeout be the second argument to the method, or zero if the argument was omitted.
  2. Apply the ToString() abstract operation to timeout, and let timeout be the result. [ECMA262] 3. Apply the ToNumber() abstract operation to timeout, and let timeout be the result. [ECMA262]
  3. If timeout is an Infinity value, a Not-a-Number (NaN) value, or negative, let timeout be zero.
  4. Round timeout down to the nearest integer, and let timeout be the result.
  5. Return timeout.

So:

http://www.ecma-international.org/ecma-262/6.0/index.html#sec-tonumber calls http://www.ecma-international.org/ecma-262/6.0/index.html#sec-toprimitive which calls valueOf

urish commented 8 years ago

So it seems like our job is already done, that's great :-)