Created
February 2, 2016 14:47
-
-
Save kebman/2294d114cc37968f83cf to your computer and use it in GitHub Desktop.
JavaScript Callback Example
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Example of using callbacks in JavaScript</title> | |
<meta charset="utf-8" /> | |
<style type="text/css"></style> | |
</head> | |
<body> | |
<header> | |
<h1>Simulation of delayed callback functionality</h1> | |
</header> | |
<article> | |
<h1>Test Area</h1> | |
<p id="pub">Waiting for response…</p> | |
</article> | |
</body> | |
<script> | |
var pub = document.getElementById("pub"); | |
function caller(data, callback) { | |
// run function | |
callback(data + " has finally arrived"); | |
} | |
function delayedFunc(input) { | |
// simulate delay in the function that is called back | |
setTimeout(function () { | |
pub.innerHTML = (input); | |
}, 1500); | |
} | |
// test run: | |
caller("The delayed data", delayedFunc); | |
/* | |
* Callbacks are often used when data retrieval is expected to be delayed. | |
* Here is a simulation of a funciton with such a delay, and how a callback can solve the delayed execution of if. | |
*/ | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment