setTimeout example 2
Using asynchronous execution to defer code *after* long processing
by Arnaud Buchholz
HTML
<input type="button" value="go" id="go">
<select id="cleaning">
<option value="0">immediate</option>
<option value="1000">1 second</option>
<option value="5000">5 seconds</option>
</select>
<div id="log"></div>
CSS
input[type=button], select {
font-family: verdana, arial, sans-serif;
font-size: 16px;
border: 0;
background-color: white;
}
body {
font-family: verdana, arial, sans-serif;
font-size: 16px;
}
JavaScript
var logDisplay = document.getElementById("log"),
cleaningDelay = 0;
function log(text) {
logDisplay
.appendChild(document.createElement("div"))
.appendChild(document.createTextNode(text));
}
var cleaningChoice = document.getElementById("cleaning");
cleaningChoice.addEventListener("change", function () {
cleaningDelay = parseInt(cleaningChoice.options[cleaningChoice.selectedIndex].value, 10);
log("Cleaning delay changed to " + (cleaningDelay / 1000) + "s");
});
document.getElementById("go").addEventListener("click", function () {
var idx;
logDisplay.innerHTML = ""; // clean the output
for (idx = 0; idx < 20; ++idx) {
log("[" + idx + "]: " + callback());
}
});
var timerId,
value;
function callback() {
if (!value) {
log("Allocating a value");
value = (new Date()).toString();
timerId = setTimeout(function () {
log("Cleaning the value");
timerId = 0;
value = 0;
}, cleaningDelay);
}
return value;
}