Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  15] [ 6]  / answers: 1 / hits: 20358  / 9 Years ago, tue, june 16, 2015, 12:00:00

I am trying to loop through an array, but want to output each value of the array with a delay. This is what my current understanding is on how it should work:



EDIT



Requested JS Fiddle: http://jsfiddle.net/d3whkjww/



    loopThroughSplittedText: function(splittedText) {

for (var i = 0; i < splittedText.length; i++) {
// for each iteration console.log a word
// and make a pause after it
setTimeout(
console.log(splittedText[i]),
1000
);
};

},


Yet, it does not work, and I believe it might be, because the arguments in the for loop have to be inside the setTimeout function. Yet I don't know how to make it work.



All I get is every value of the array at once, but I want them appear with a delay. How do I do that?


More From » arrays

 Answers
23

In my example, it will show you how to loop through an array contentiously until you stop. This is to just give you an idea on how you can do the delay. Also it shows you when the value actually got displayed.



I would say that you could actually create a nice utility from this timer, and use it for multiple purposes and with the utility it'll stop you from repeating large chunks of code.



JavaScript Loop example:





var body = document.body;
var splittedText = [Hello, World, How, Are, You, Today];

loopThroughArray(splittedText, function (arrayElement, loopTime) {
body.innerHTML += arrayElement+ : + loopTime+ <br/>;
}, 1000);

function loopThroughArray(array, callback, interval) {
var newLoopTimer = new LoopTimer(function (time) {
var element = array.shift();
callback(element, time - start);
array.push(element);
}, interval);

var start = newLoopTimer.start();
};

// Timer
function LoopTimer(render, interval) {
var timeout;
var lastTime;

this.start = startLoop;
this.stop = stopLoop;

// Start Loop
function startLoop() {
timeout = setTimeout(createLoop, 0);
lastTime = Date.now();
return lastTime;
}

// Stop Loop
function stopLoop() {
clearTimeout(timeout);
return lastTime;
}

// The actual loop
function createLoop() {
var thisTime = Date.now();
var loopTime = thisTime - lastTime;
var delay = Math.max(interval - loopTime, 0);
timeout = setTimeout(createLoop, delay);
lastTime = thisTime + delay;
render(thisTime);
}
}




[#66191] Saturday, June 13, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsleyashlynnh

Total Points: 64
Total Questions: 119
Total Answers: 98

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;