I have a project that prints sentences from a large array to the screen.
Using this Javascript: Loop through Array with Delay I was able to get it working. However, there are two things that I would like to achieve. Although I can print elements line by line, I would like to incorporate line spaces at some points so for example :
var splittedText = [“This is the first paragraph ", “and it tells a story.”, ***line space empty here**, “this is the second paragraph “, “and it tells another story.”];
should print to screen:
This is the first paragraph
and it tells a story
This is the second paragraph
and it tells another story
Second question:
I would like for the text to clear off the lines off the screen after x amount of lines so in the case above after 4 lines (including space) it would clear and just print
and it tells another story
However, if there were more lines it would continue printing
so lines 1-4 will be cleared 5 will appear, then 6, 7, 8 5,6,7 will be cleared then 8, 9 ,10, 11 and so on
Essentially it should be similar to a scrolling effect
When final line is reached it will reiterate and start process again. Full code here:
</style>
<div id="o"></div>
<script>
var body = document.body;
var splittedText = [“This is the first paragraph ", “and it tells a story.”, “line space empty here “, “this is the second paragraph “, “and it tells another story.”];
loopThroughArray(splittedText, function (arrayElement, loopTime) {
body.innerHTML += arrayElement + "<br/>";
}, 2000);
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);
}
}
</script>