JSFiddle - React, Tailwind, and code Playground
by Andrew Gerst
HTML
<button onclick="delayedAlert();">
show an alert box after 2 seconds
</button><br>
<button onclick="clearAlert();">Cancel</button>
JavaScript
// Example 1
function delayedAlert() {
timeoutID = window.setTimeout(slowAlert, 2000);
}
function slowAlert() {
alert("That was really slow!");
}
function clearAlert() {
window.clearTimeout(timeoutID);
}
// Example 2
function generateOutput(aConcise) {
if (aConcise) {
parent.generateConciseOutput();
} else {
parent.generateOutput();
}
}
window.setTimeout(generateOutput, 1000, true);
// won't pass "true" to the generateOutput in IE
// Increase compatibility with unnamed functions
window.setTimeout(
function() {
generateOutput(true);
},
1000
); // will work with every browser
window.setTimeout('window.parent.generateOutput(true)', 1000);
// deprecated
// Example 3
// Correct
window.setTimeout(function() {
alert("Hello World!");
}, 500);
// Incorrect
window.setTimeout("alert(\"Hello World!\");", 500);
/* String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code. */