Last active
February 15, 2016 09:59
-
-
Save bzdgn/5e7a8e471676c908082e to your computer and use it in GitHub Desktop.
JavaScript Callback with Anonymous Function Demo
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
<html> | |
<body> | |
<h1>OUTPUT;</h1> | |
<p id="demo"></p> | |
<script> | |
"use strict"; | |
var maxTime = 1000; | |
var outbox = document.getElementById("demo"); | |
var evenDoubler = function(input, callback) { | |
var waitTime = Math.floor(Math.random()*(maxTime+1)); | |
if(input%2) { | |
setTimeout(function () { | |
callback(new Error("Odd Input")); | |
}, waitTime); | |
} else { | |
setTimeout(function () { | |
callback(null, input*2, waitTime); | |
}, waitTime); | |
} | |
}; | |
var handleResults = function(error, results, time) { | |
}; | |
var count = 0; | |
var i; | |
for(i = 1; i <= 20; i++) { | |
evenDoubler(i, function(error, results, time) { | |
var output; | |
if(error) { | |
output = "ERROR: " + error.message; | |
} else { | |
output = "The results: " + results + " (" + time + " ms)"; | |
} | |
outbox.innerHTML += output + '<br>'; | |
console.log(output); | |
if (++count === 20) { | |
outbox.innerHTML += "Done !"; | |
} | |
}); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment