Übung 05 - Asynchron
5.1 - Promises
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Promises</title>
<script>
Promise.all([
fetch('https://www2.inf.h-brs.de/~mbeck32s/A.txt').then(res => res.text()),
fetch('https://www2.inf.h-brs.de/~mbeck32s/B.txt').then(res => res.text())
]).then(data => {
let arra = data[0].split('\r');
let arrb = data[1].split('\r');
arrb.forEach(function (ael, index) {
this[index] = '<span style="color:blue;">' + ael + '</span>';
}, arrb)
// interleave function taken from Mulan on stackoverflow
// https://stackoverflow.com/a/47061616/15212696
const interleave = ([x, ...xs], ys = []) =>
x === undefined
? ys // base: no x
: [x, ...interleave(ys, xs)] // inductive: some x
const text = interleave(arra, arrb);
document.getElementById("text").innerHTML = text.join('<br />');
})
</script>
</head>
<body style="text-align: center; font-family: 'Calibri',serif">
<h1>5.1 Promises - Konkateniert zwei Texte, die auf meinem Server liegen, zeilenweise.</h1>
<p id="text"></p>
</body>
</html>
5.2 - Async Await
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Async/Await</title>
<script>
async function mixTexts() {
const [a, b] = await Promise.all([
fetch('https://www2.inf.h-brs.de/~mbeck32s/A.txt'),
fetch('https://www2.inf.h-brs.de/~mbeck32s/B.txt')
]);
let arra = (await a.text()).split('\r');
let arrb = (await b.text()).split('\r');
arrb.forEach(function (ael, index) {
this[index] = '<span style="color:blue;">' + ael + '</span>';
}, arrb)
// interleave function taken from Mulan on stackoverflow
// https://stackoverflow.com/a/47061616/15212696
const interleave = ([x, ...xs], ys = []) =>
x === undefined
? ys // base: no x
: [x, ...interleave(ys, xs)] // inductive: some x
const text = interleave(arra, arrb);
document.getElementById("text").innerHTML = text.join('<br />');
}
mixTexts();
</script>
</head>
<body style="text-align: center; font-family: 'Calibri',serif">
<h1>5.2 async/await - Konkateniert zwei Texte, die auf meinem Server liegen, zeilenweise.</h1>
<p id="text"></p>
</body>
</html>
5.3 - Web Worker
primzahlen.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Primzahlen</title> <style> div { width: 100%; height: 4em; } #container { background-color: lightgrey; } #animate { background-color: yellow; } </style> </head> <body style="font-family: Calibri,serif"> <h1>5.3 Worker - Web Worker, der Primzahlen berechnet.</h1> <p>Die Berechnung startet erst nach 3 Sekunden, um Ruckel(freiheit) besser zu erkennen. Die Schleife läuft nur bis Index 9999, da eine Endlosschleife bei mir dafür sorgt, dass die Seite keine Rückmeldung mehr gibt.</p> <div id="container"> <div id="animate"></div> </div> <div id="prime" style="overflow-wrap: break-word"></div> </body> <script> function fib(max) { let cache = []; /* Endlosschleife: let i = 0; for (;;){ */ for (let i = 0; i < max ; i++) { if (i === 0 || i === 1) { cache.push(BigInt(i)); document.getElementById("prime").innerText = "Index: " + i + " Fibonacci: " + i; continue; } const next = cache[cache.length - 2] + cache[cache.length - 1]; cache.push(next); console.log("Index: " + i + " Fibonacci: " + next); document.getElementById("prime").innerText = "Index: " + i + " Fibonacci: " + next; } } function anim() { const animate = document.getElementById("animate"); let width = 1; let animation = requestAnimationFrame(step); function step() { width += 1; if (width === 100) width = 1; // repeat animate.style.width = width + '%'; animation = requestAnimationFrame(step); } } anim(); setTimeout(function (){ // fib() fib(10000); }, 3000); </script> </html>
primeWorker.jsonmessage = function () { let i = 0; let cache = []; for (; ; i++) { if (i === 0 || i === 1) { cache.push(BigInt(i)); self.postMessage("Index: " + i + " Fibonacci: " + i) continue; } const next = cache[cache.length - 2] + cache[cache.length - 1]; cache.push(next); postMessage("Index: " + i + '<br>' + " Fibonacci: " + next) } }
worker.html (as seen live here)<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Worker</title> <style> div { width: 100%; height: 4em; } #container { background-color: lightgrey; } #animate { background-color: yellow; } </style> </head> <body> <div id="container"> <div id="animate"></div> </div> <div id="prime" style="overflow-wrap: break-word"></div> </body> <script> function anim() { const animate = document.getElementById("animate"); let width = 1; let animation = requestAnimationFrame(step); function step() { width += 1; if (width === 100) width = 1; // repeat animate.style.width = width + '%'; animation = requestAnimationFrame(step); } } anim(); const worker = new Worker('primeWorker.js') worker.postMessage('letsgo'); worker.onmessage = function (event){ document.getElementById("prime").innerHTML = event.data; } </script> </html>
5.4 WWW Navigator
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WWW Navigator</title>
<script>
let content;
let selectedTop;
let t;
let selectedLeft;
async function getContent() {
fetch('https://www2.inf.h-brs.de/~mbeck32s/navigator_contents.json')
.then(res => res.json())
.then((js) => {
content = js;
selectedTop = js['html'];
selectedLeft = Object.keys(selectedTop)[0];
const urlParams = new URLSearchParams(window.location.search);
const top = urlParams.get('top');
const left = urlParams.get('left');
if(top !== null) topnav(top);
if(left !== null) sidenav(left);
})
}
getContent();
function sidenav(title) {
const btns = document.getElementsByClassName('left-sidebar')[0].getElementsByTagName('button');
for (let i of btns) {
console.log(i)
i.style.backgroundColor = '#6a709f'
}
document.getElementById(`${title}`).style.backgroundColor = 'antiquewhite'
selectedLeft = content[t][title];
document.getElementById("main").innerHTML = selectedLeft.content;
document.getElementById("urls").innerHTML = "";
for (let el of selectedLeft.references) {
document.getElementById("urls").innerHTML += `<a style="overflow-wrap: anywhere" href="${el}">${el}</a>`;
}
setLinks();
}
function topnav(title) {
const btns = document.getElementsByTagName('header')[0].getElementsByTagName('button');
for (let i of btns) {
i.style.backgroundColor = '#6a709f'
}
console.log(title)
document.getElementById(`${title}`).style.backgroundColor = 'antiquewhite'
t = title;
selectedTop = content[title.toLowerCase()]
document.getElementsByClassName('left-sidebar')[0].innerHTML = "";
for (let el in selectedTop) {
if (el !== 'basics') document.getElementsByClassName('left-sidebar')[0].innerHTML += `<button id="${el}" onclick="sidenav('${el}')">${el}</button>`
}
document.getElementById("main").innerHTML = content[t].basics.content;
document.getElementById("urls").innerHTML = "";
for (let el of content[t].basics.references) {
document.getElementById("urls").innerHTML += `<a style="overflow-wrap: anywhere" href="${el}">${el}</a>`;
}
setLinks();
}
function setLinks() {
let links = document.getElementById("main").getElementsByTagName("a");
for (let a of links) {
if (a.innerText.toLowerCase() === 'html' || a.innerText.toLowerCase() === 'css' || a.innerText.toLowerCase() ==='javascript') {
console.log(a.innerText)
a.href = window.location.href.split('?')[0] + '?top=' + a.innerText.toLowerCase();
continue;
}
a.href = window.location.href.split('?')[0] + '?top=' + t + '&left=' + a.innerText.toLowerCase();
}
}
</script>
<style>
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
color: white;
text-align: center;
}
header {
background-color: #c14f4f;
text-align: left;
}
main {
background-color: #6a9ebd;
font-size: 1.5rem;
color: black;
}
main a{
font-size: 1.5rem;
color: black;
}
footer {
background: black;
}
.left-sidebar {
background-color: #c28281;
}
.right-sidebar {
text-align: left;
background-color: #c28281;
}
.container {
display: flex;
width: 100%;
flex-direction: column;
height: 100vh;
}
.content {
display: flex;
flex-direction: column;
overflow-y: auto;
height: 100vh;
}
button {
background-color: #6a709f;
color: black;
border-top-color: white;
border-left-color: white;
border-bottom-color: #9a9a9a;
border-right-color: #9a9a9a;
border-radius: 20px;
font-weight: bold;
padding: 0.3em 2em;
margin: 1em;
}
button:hover {
background-color: antiquewhite;
}
.left-sidebar button {
display: block;
}
h1 {
text-align: center;
margin: 0;
}
a {
color: white;
font-size: small;
}
@media all and (min-width: 768px) {
.content {
flex-direction: row;
flex-wrap: wrap;
}
main {
flex: 5;
order: 2;
}
.left-sidebar {
order: 1;
flex: 1;
font-size: 2em;
}
.right-sidebar {
flex: 1;
order: 3;
font-size: 2em;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>WWW-Navigator</h1>
<button id='html' onclick="topnav('html')">HTML</button>
<button id='css' onclick="topnav('css')">CSS</button>
<button id='javascript' onclick="topnav('javascript')">JavaScript</button>
<button>Other</button>
</header>
<div class="content">
<aside class="left-sidebar" style="display: block">
</aside>
<main id="main">
</main>
<aside class="right-sidebar">
<h6>External resources:</h6>
<div id="urls"></div>
</aside>
</div>
<footer>
<span style="font-size: 30px">Footer:</span>
<a href="">Sitemap</a>
<a href="">Home</a>
<a href="">News</a>
<a href="">Contact</a>
<a href="">About</a>
</footer>
</div>
</body>
</html>