+ 1

Javascript loop in slow motion

Hi. I have simple js code. I want this loop work in slow motion. Say one second interval for each letter. How do I know my loop has worked? thanks var letter = ["A", "B", "C", "D","E"]; var i = 0; function change(){ for (i=0; i < letter.length ; i++){ document.getElementById("demo").innerHTML = letter [i]; }; };

13th Sep 2018, 8:13 AM
Anita Putri
Anita Putri - avatar
8 Answers
+ 2
CalviŐ˛ .thanks
13th Sep 2018, 1:54 PM
Anita Putri
Anita Putri - avatar
+ 10
You can to use setInterval/setTimeout to allow control over the delay of the next call window.onload = function(){ var letter = ["A", "B", "C", "D","E"]; var i = 0; var interval = null; function change(){ document.getElementById("demo").innerHTML += letter[i]; ++i; if(i >= letter.length){ clearInterval(interval); } }; interval = setInterval(change, 1000); }
13th Sep 2018, 8:28 AM
Burey
Burey - avatar
+ 4
Here is another way using modern JavaScript methods: async and await var arr = ["A","B","C","D"]; async function delayPush() { out = document.getElementById("out"); for(a of arr) { out.innerText += a; await new Promise((resolve,reject)=>setTimeout(resolve,1000)); } } https://code.sololearn.com/WtY7OQdVBiOB/?ref=app
17th Sep 2018, 3:50 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 4
Another modern JavaScript way: using Generator var arr = ['A','B','C','D','E']; var runDelay = genDelayPush(); var tmr = setInterval(delayInterval, 2000); function * genDelayPush() { var out = document.getElementById('out'); for(var a of arr) yield a; } function delayInterval() { if(d=runDelay.next().value) out.innerText += d; else clearInterval(tmr); } https://code.sololearn.com/Wyx4w0yUd6o3/?ref=app
18th Sep 2018, 4:00 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 3
13th Sep 2018, 9:25 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 1
CalviŐ˛ . thanks
17th Sep 2018, 4:22 AM
Anita Putri
Anita Putri - avatar
+ 1
CalviŐ˛ . wow..thanka Calvin. I am newbie here. Very beginner. what I am doing here is try to understand JavaScript. I make code and other codes and then find out why the output become that or this.
18th Sep 2018, 8:02 AM
Anita Putri
Anita Putri - avatar
0
Burey . thanks
13th Sep 2018, 1:53 PM
Anita Putri
Anita Putri - avatar