Beispiel:Promise-showcase-1.html
Aus SELFHTML-Wiki
<!DOCTYPE HTML>
<html lang="de">
<head>
<meta charset="utf-8">
<title>Beispiel: Promise-basierender Timer</title>
<style>
#ausgabe {
white-space: pre-line;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Ausgabe in ein div statt auf die Konsole, damit man es auch ohne DevTools sieht
const ausgabeBox = document.getElementById("ausgabe");
function ausgabe(text) {
ausgabeBox.textContent += text + "\n";
}
function delay(millisekunden, wert) {
function timerController(resolve, reject) {
setTimeout(timerComplete, millisekunden);
function timerComplete() {
resolve(wert);
}
}
return new Promise(timerController);
}
delay(1000, "Welt")
.then(text => ausgabe(text));
ausgabe("Hallo");
});
</script>
</head>
<body>
<h1>Beispiel: Promise-basierender Timer</h1>
<fieldset>
<legend>Programmausgaben</legend>
<div id="ausgabe"></div>
</fieldset>
</body>
</html>