问题描述
如何在JavaScript中创建无限循环?我正在尝试制作幻灯片,我已经开始工作了,但我无法让它循环播放。我甚至无法让它循环两次。
How do I make an infinite loop in JavaScript? I'm trying to make a slideshow, which I have working, but I can't get it to loop. I can't even get it to loop twice.
我现在使用的代码是
window.onload = function start() {
slide();
}
function slide() {
var num = 0;
for (num=0;num<=10;num++) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
如果没有那里的东西,它确实会通过一旦。当我输入一个for时,它要么让Firefox锁定,要么只循环一次。我确信这是一件非常简单的事情,即使它必须循环1,000,000次而不是无限次,这对我来说还算合适。
Without the for thing in there, it does go through once. When I put in a for, it either makes Firefox lock up, or just loops once. I'm sure this is a really simple thing to do, and even if it has to be loop 1,000,000 times or something instead of infinite, that'd work fine for me.
另外,我不想使用jQuery或别人创建的东西。我正在学习JavaScript,这部分是为了帮助我学习,部分是因为我正在努力制作尽可能多的基于HTML5的系统。
Also, I don't want to use jQuery or something that someone else created. I'm learning JavaScript, and this is partially to help me learn, and partially because I'm trying to make as many HTML5-based systems as I can.
编辑:我认为它冻结的原因是因为它一次执行代码,然后只是将它存储在缓存中。我想要它做的就是经历一次,然后再次从顶部开始,这是我一直认为循环的地方。在批处理(命令提示符)脚本中,可以使用 GOTO
命令完成此操作。我不知道JS中是否有相应的,但这确实是我的目标。
I think the reason it's freezing is because it executes the code all at once, and then just stores it in a cache or something. What I want it to do is go through this once, then start at the top again, which is what I've always thought loops where for. In "batch" (command prompt) scripting, this could be done with a "GOTO
" command. I don't know if there's an equivalent in JS or not, but that's really my goal.
推荐答案
正确的方法是使用单个计时器。使用 setInterval
,您可以实现以下目标:
The correct approach is to use a single timer. Using setInterval
, you can achieve what you want as follows:
window.onload = function start() {
slide();
}
function slide() {
var num = 0, style = document.getElementById('container').style;
window.setInterval(function () {
// increase by num 1, reset to 0 at 4
num = (num + 1) % 4;
// -600 * 1 = -600, -600 * 2 = -1200, etc
style.marginLeft = (-600 * num) + "px";
}, 3000); // repeat forever, polling every 3 seconds
}
这篇关于JavaScript无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!