public
Last active

Check for truth at a specified interval

  • Download Gist
README.md
Markdown

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
meanwhile.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
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)
)
}
}
package.json
JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
{
"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"
}
test.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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)

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.