Skip to content

Instantly share code, notes, and snippets.

@hugs
Last active May 10, 2022 09:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugs/6896964 to your computer and use it in GitHub Desktop.
Save hugs/6896964 to your computer and use it in GitHub Desktop.
The most ridiculously awesome way to sleep synchronously in Node.js
http://creativecommons.org/publicdomain/zero/1.0/
CC0 1.0 Universal (CC0 1.0)
Public Domain Dedication
To the extent possible under law, Jason Huggins has waived all copyright and related or neighboring rights to sleep-example.js and sleep-server.js.
This work is published from: United States.
// Client - Run this in a second terminal window:
// Requires http-sync (https://github.com/dhruvbird/http-sync) and libcurl.
var http_sync = require('http-sync');
var sleep = function(seconds) {
var req = http_sync.request({
host: 'localhost',
port: 8000,
path: '/' + seconds
}).end();
}
// Usage:
sleep(1); // sleep one second
// This is equivalent to (but more ridiculously awesome than) the following code in Python:
// >>> from time import sleep
// >>> sleep(1)
// Server - Run this in a terminal window:
var http = require("http"),
url = require("url");
http.createServer(function (req,res) {
var sleep_amount = url.parse(req.url).path.split('/')[1];
res.writeHead(200, {'Content-Type': 'text/plain'});
setTimeout(function () {
res.end();
}, sleep_amount * 1000);
console.log('Number of seconds to sleep: ' + sleep_amount);
}).listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment