+ 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]; }; };
8 Antworten
+ 2
Calviղ .thanks
+ 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);
}
+ 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
+ 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
+ 3
Promise and recursive way :)
https://code.sololearn.com/WEFh7LrxV0KX/?ref=app
+ 1
Calviղ . thanks
+ 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.
0
Burey . thanks