Skip to content

Instantly share code, notes, and snippets.

@heapwolf
Last active December 14, 2015 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heapwolf/5105621 to your computer and use it in GitHub Desktop.
Save heapwolf/5105621 to your computer and use it in GitHub Desktop.
Check for truth at a specified interval

NAME

meanwhile(3)

SYNOPSIS

Some setInterval sugar. A program keeps running, meanwhile a check is performed at a specified interval and if the resut is true, a callback gets called.

EXAMPLE

var meanwhile = require('meanwhile')
var x = false

meanwhile(
  function() { return x },
  function() { console.log('x is now true') }
)

x = true
module.exports = function meanwhile(condition, callback, interval, maxTries) {
if (!meanwhile.collection) {
meanwhile.collection = []
}
function clear(index) {
clearInterval(meanwhile.collection[index])
delete meanwhile.collection[index]
}
var result = condition()
if (result) {
callback(result)
}
else {
meanwhile.collection.push(
setInterval((function(index) {
return function() {
result = condition()
if (result) {
clear(index)
callback(result)
}
else if (--maxTries === 0) {
clear(index)
}
}
})(meanwhile.collection.length), interval || 16)
)
}
}
{
"name": "meanwhile",
"version": "0.0.2",
"description": "check for truth at a specified interval, meanwhile keep working",
"main": "meanwhile.js",
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "https://gist.github.com/5105621.git"
},
"keywords": [
"flow"
],
"author": "hij1nx",
"license": "MIT"
}
var assert = require('assert');
var meanwhile = require('./meanwhile');
var x = false, y = false
meanwhile(
function() { return x },
function() { y = true; assert.ok('The callback was called') }
)
setTimeout(function() {
x = true
}, 100)
setTimeout(function() {
if (y === false) {
assert.fail('The callback was not called')
}
}, 200)
@heapwolf
Copy link
Author

heapwolf commented Mar 8, 2013

I did this module to see how it feels to publish to npm from a gist. it works great and feels lite-weight.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment