[英]How to re-loop a setInterval/setTimeout function
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)
我正在使用setInterval或setTimeout(不确定哪个)进行此操作
So if a user submits 2 entries into a text-box form, those 2 entries will be displayed, one after another, repeatedly. 因此,如果用户以文本框形式提交2个条目,则将重复显示这2个条目,一个接一个。
What follows is my code, taken from: jsfiddle.net/sean1rose/sKadX/4/ 以下是我的代码,摘自: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). 就像我现在的代码一样,如果您在表单中一个接一个地输入2个不同的字符串,则将一个接一个地显示(带有延迟),但是它将停在最后一个(不会重新显示)。环)。
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)...
(希望这也可以用于2个以上的输入。例如,如果用户输入5个不同的条目,则它将循环并反复显示这5个)。
I've modified your fiddle a bit. 我对您的小提琴做了一些修改。 Now the
frm.submit
event looks like: 现在,
frm.submit
事件看起来像:
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
) 编辑:对于您的后续问题,我用单击的
p
标签的索引splice
了container
数组(使用jQuery的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: 我还修改了
frm.submit
事件,现在它看起来像:
oldHandle = setInterval(function () {
output.text(container[i++%container.length]);
}, 500)
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/ 小提琴: http : //jsfiddle.net/tCw8Q/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.