selbekk

Introducing Timeproxy

April 20, 2018
2 min read

Every once in a while, you need to make sure something happens every so often. Or fails within a reasonable time frame. Or do anything related to time. I am about to make your life so much better.

I write a lot of timing constants. It’s not really a lot of work, but they all kind of look like this:

const REQUEST_TIMEOUT = 1000 * 20;
const COOKIE_EXPIRY_TIME = 1000 * 60 * 60 * 24 * 7;
const DEBOUNCE_PERIOD = 500;

The constants are named correctly enough, but I always have to do some quick math whenever I revisit my code. It’s just not very readable! How long is 1000 * 60 * 60 * 12 * 2, really? 🤷‍

Introducing Timeproxy!

timeproxy is a very tiny, blazingly fast and production ready library (991 bytes gzipped) that lets you write god damn beautiful constants! It uses a fancy “new” ES2015 feature called proxies to make your constants chill af. Don’t worry about the tech, just enjoy the dopeness:

import tp from 'timeproxy';

const REQUEST_TIMEOUT = tp.TWENTY_SECONDS;
const COOKIE_EXPIRY_TIME = tp.A_WEEK;
const DEBOUNCE_PERIOD = tp.HALF_A_SECOND;

This way, you can express your intent AND the amount of time, without having to deal with math at all. Also, it just reads so much better!

Thanks to some great feedback after this article was published, I’ve added support for using timeproxy as a tagged template literal as well:

import tp from 'timeproxy';

const REQUEST_TIMEOUT = tp`twenty seconds`;
const COOKIE_EXPIRY_TIME = tp`1 week`;
const DEBOUNCE_PERIOD = tp`.5 seconds`;

Notice that you can use numbers or strings to specify your amounts — this even works with the “fake property” approach. Due to limitations in JavaScript, you can’t start a “fake property” with a number, though you can with tagged template literals.

Here’s a few more examples:

import tp from 'timeproxy';

const TIME_UNTIL_NEXT_PUSH = tp.ONE_WEEK_AND_A_DAY;
const SHOW_DONT_LEAVE_DELAY = tp.TWELVE_MINUTES_TWO_SECONDS;
const WOW = tp.NINE_WEEKS_TWELVE_DAYS_SEVEN_MINUTES_AND_HALF_A_SECOND;

// or

const TIME_UNTIL_NEXT_PUSH_TS = tp`one week and a day`;
const SHOW_DONT_LEAVE_DELAY_TS = tp`12 minutes 2 seconds`;
const WOW_TS = tp`9 weeks twelve days and .5 seconds`;

Another feature is relative time. If you want your timestamp to be relative to the current time, prefix with in or suffix with ago.

import tp from 'timeproxy';

const SESSION_EXPIRES = tp.IN_THIRTY_SECONDS;
const OLD_POST_TIMESTAMP = tp`two weeks ago`;

My goal with this library is that it will let you write your constants with natural language. Write what you feel like might make sense, and it will probably just work.

I hope you dig it!

$ npm install timeproxy

All rights reserved © 2024