Reputation: 325
I am trying to re-loop the display of user-inputted string. I am doing this using either setInterval or setTimeout (not sure which one)
So if a user submits 2 entries into a text-box form, those 2 entries will be displayed, one after another, repeatedly.
What follows is my code, taken from: jsfiddle.net/sean1rose/sKadX/4/
frm.submit(function(event) {
event.preventDefault();
container.push(txtBox.val());
var i = 0;
function myLoop(){
setInterval(function () {
output.text(container[i]);
i++;
if (i < container.length) {
myLoop();
}
}, 3000)
}
myLoop();
txtBox.val('');
});
As my code is now, if you input 2 different strings into the form, one after another, it will display one after the other (w/ a delay), but then it will stop at the last one (it won't re-loop).
How would I fix the code to get it to continuously re-loop the input so that it doesn't stop at the last inputted string, but instead restart at and display the 1st inputted string? (This should hopefully also work for more than 2 inputs. For example, if a user inputs 5 different entries, then it will loop thru and display those 5 over and over again)...
Upvotes: 0
Views: 233
Reputation: 7308
I've modified your fiddle a bit. Now the frm.submit
event looks like:
frm.submit(function (event) {
event.preventDefault();
container.push(txtBox.val());
var i = 0; // to initialize the index
clearInterval(oldHandle); //to make sure only one setInterval is running at any time
oldHandle = setInterval(function () {
output.text(container[i]);
i++;
if (i == container.length) { //this re-loops your container array once the last element is reached
i = 0; //reset the index
}
}, 500)
txtBox.val('');
});
Edit: For your follow-up question, I've splice
d the container
array with the index of the p
tag clicked(using jQuery's prevAll
)
$(".controlbox").on('dblclick', 'p', function () {
container.splice($(this).prevAll('p').length, 1);
$(this).remove();
});
I've also modified the frm.submit
event, now it looks like:
oldHandle = setInterval(function () {
output.text(container[i++%container.length]);
}, 500)
Upvotes: 1
Reputation: 1396
frm.submit(function(event) {
event.preventDefault();
container.push(txtBox.val());
console.log(container);
function myLoop(){
setInterval(function () {
var str="";
for(var i=0;i<container.length;i++){
str+=container[i]+"<br>";
}
output.html(str)
myLoop();
}, 3000)
}
myLoop();
txtBox.val('');
});
fiddle:http://jsfiddle.net/tCw8Q/
Upvotes: 0