Created
September 28, 2012 11:45
-
-
Save robshep/3799341 to your computer and use it in GitHub Desktop.
Mutex for overlapping online queue dispatching in JS (node)
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
var $ = require("jquery"); | |
var things = ["a", "b", "c", "d", "e", "f"]; | |
var mutex = 0; | |
var onSuccess = function( data){ | |
console.log(" Success: " + data + " [" + mutex + "]"); | |
var sentThing = things.shift(); | |
console.log(" Dequeue item: " + sentThing + " [" + mutex + "]") | |
mutex--; | |
send(); | |
} | |
var onError = function(data) { | |
console.log(" Error: " + data + " [" + mutex + "]") | |
mutex--; | |
} | |
var send = function() { | |
var mutexWas = mutex++ | |
if( mutexWas > 0 ){ | |
console.log(" Something is already active - giving up [" + mutex + "]"); | |
mutex--; | |
return; | |
} | |
else { | |
if(things.length > 0) { | |
console.log(" Attempting send [" + mutex + "]") | |
var thing = things[0]; | |
$.get("http://muon.datacymru.net:81/tmp/sendandwait.php?thing="+thing).success(onSuccess).error(onError); | |
} | |
else { | |
console.log(" Nothing to send [" + mutex + "]") | |
mutex--; | |
} | |
} | |
} | |
var checkOnline = function() { | |
console.log("We are online [" + mutex + "]"); | |
send(); | |
setTimeout(checkOnline, 1000); | |
} | |
setTimeout(checkOnline, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment