Files
JS/02_advanced/uebungen/u11_pyramide-break/index.js
T
2026-09-24 10:25:47 +02:00

56 lines
1.3 KiB
JavaScript

// Variante 1
const printWords = (text = '', idx = 0) => {
const words = text.split(' '); //=> ['KI-Entwickler', 'warnen', 'UN-Gremium']
// Basisfall
if (idx >= words.length) return; // Abbruch
console.log(words[idx]); // KI-Entwickler
setTimeout(() => {
printWords(text, ++idx);
}, 1000);
};
// printWords('KI-Entwickler warnen UN-Gremium');
const printWordsFor = (sentence) => {
const wordArr = sentence.split(' ');
for (let i = 0; i < wordArr.length; i++) {
setTimeout(() => {
console.log(wordArr[i]);
}, 1000 * i);
}
};
printWordsFor('Bundestag berät über Organspende');
// setTimeout(() => {
// console.log('The');
// setTimeout(() => {
// console.log('pyramid');
// setTimeout(() => {
// console.log('of');
// setTimeout(() => {
// console.log('doom');
// setTimeout(() => {
// console.log('keeps');
// setTimeout(() => {
// console.log('growing.');
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// }, 1000);
// Übung 11: Die Pyramide abbrechen
// Schreibe das Codebeispiel 96 so um, dass keine Pyramide entsteht. Benutze dazu, wie im Text angedeutet, eine Funktion, die das n-te Wort ausgibt und sich per setTimeout(…) mit n + 1 als Parameter aufruft, solange noch Wörter im Satz vorhanden sind.