froatsnook:sleep

v1.1.0Published 10 years ago

This package has not had recent updates. Please investigate it's current state before committing to using it in your project.

Fiber-friendly sleep statements (server only)

Example

1console.assert(Meteor.isServer); // Meteor.sleep only works on the server
2Meteor.sleep(1000); // ms
1console.assert(Meteor.isServer); // Meteor.sleepUntil only works on the server
2Meteor.sleepUntil(new Date(2020, 3, 1));

Why?

Meteor's fibers let you wait (i.e. during I/O) without blocking the event loop. But the greatest of all ways to wait has been unattainable until now. This package lets you sprinkle sleep statements throughout your code to convince your boss to buy better hardware. Or to rate-limit your API usage without using setTimeout.

1// Shopify wants no more than two events per second.
2var results = [];
3for (var i = 0; i < numPages; i++) {
4    Meteor.sleep(500);
5
6    var currentPage = FetchOrders(i);
7    results = results.concat(currentPage);
8}
9HandleResults(results);

Alternatives

The real advantage is code clarity. The following examples demonstrate how this code might be written in the browser (where fibers are not available).

1// plain javascript
2var results;
3(function fetcher(i) {
4    if (i === 5) {
5        HandleResults(results);
6        return;
7    }
8
9    var currentPage = FetchOrders(i);
10    results = results.concat(currentPage);
11    Meteor.setTimeout(function() {
12        fetcher(i + 1);
13    }, 500);
14})(0);
1// async.js
2async.concatSeries(_.range(5), function(i, callback) {
3    var currentPage = FetchOrders(i);
4    Meteor.setTimeout(function() {
5        callback(null, currentPage);
6    }, 500);
7}, function(err, results) {
8    HandleResults(results);
9});

Setup

  • Install meteor add froatsnook:sleep

License

MIT