Last active
May 10, 2022 09:48
-
-
Save hugs/6896964 to your computer and use it in GitHub Desktop.
The most ridiculously awesome way to sleep synchronously in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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