I just discovered a neat JavaScript feature that I felt like sharing.
While trying to implement a function that would capture key strokes for certain patterns, like some kind of trigger, I had to compare two dates to get the number of seconds elapsed since the last keystroke.
I first thought to just create a date object, get the seconds and subtract them. But then I would have a problem with long interruptions, which could lead to unpredictable bugs. I could add minutes, but for hour long interruptions, the bug would remain and so on.. Which eventually leads to nearly full date comparison .. yurk.
Then I started missing Python with its awesome ability to compare almost any object types. At this point it hit me, could it be ? .. no ..
I opened Firebug;
>>> a = new Date();
Thu May 21 2009 20:33:14 GMT-0400 (EDT)
>>> b = new Date();
Thu May 21 2009 20:34:15 GMT-0400 (EDT)
>>> a < b
true
>>> a > b
false
>>> a == b
false
>>> a - b
-60596
>>> b - a
60596
I almost cried of joy.
After nearly three years of intensive JavaScript programming it still amaze me. Why I didn't knew about this and why I did not saw this being used anywhere else until now is beyond my understanding.
I'm still not quite sure how it process these though ..
>>> b * a
1.544930730887957e+24
>>> b / a
1.000000048751666
Modulo (%) also works but seems to only do a subtraction.
It's just using the millisecond representation of the Date object. You can do the same thing by using the .getTime() method - I'm not sure but I suspect that your way may not work on every browser.
You think you're excited? I only just found out reading this that I can run javascript directly in Firebug! I've never had that extra pane open before! thank you.
very cool & good tip, thank you very much for sharing.
Can you share this snippet on my JavaScript site, http://javascriptbank.com/submit/ ?
Thank
A Date is a timestamp (in ms), so a Number, new Date().valueOf() - no big surprise here.
v8 has some interesting usage of the modulo:
http://v8.googlecode.com/svn/trunk/src/date-delay.js
Cheers
Thank you for your info ,welcome to read this info: http://www.goodpuma.com