我已经创建了一个打字机,它工作正常。唯一的问题是我无法使代码循环。有什么简单的方法可以做到吗?我的错误在哪里?我想它不会循环,因为如果我做一个循环,它比函数中的延迟“更快”。
我的代码是JavaScript。 我希望它永久循环,但是我也尝试了普通的for循环,即使这样也没有循环。
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = dd + '/' + mm + '/' + yyyy;
var i = 0;
var txt = 'welcome to IDM...' + today + "!";
var speed = 50;
var t = true;
var loopTime = 50; // How often in milliseconds the loop should
//be run
var intervalId = setInterval(typeWriter(), 50);
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i);
i++;
setTimeout(typeWriter, speed);
} else {
k = txt.length;
(function theLoop(k) {
setTimeout(function() {
document.getElementById("demo").innerHTML =
txt.substring(0, k);
if (k--) {
i--;
// If i > 0, keep going
theLoop(k); // Call the loop again,
//and pass it the current value of i
}
}, 200);
})(txt.length);
}
}
我需要该程序永久循环。
答案 0 :(得分:0)
您可以在大型函数中添加代码,然后执行以下操作:
function largeFunction() {
// Add code here
}
var loopTime = 50; // How often in milliseconds the loop should be run
var intervalId = setInterval(largeFunction, loopTime);
这是setInterval
运行正常的一个小例子:
var count = 0;
function largeFunction() {
document.querySelector("#count").textContent = count++;
}
var loopTime = 1E3;
var intervalId = setInterval(largeFunction, loopTime);
<div id="count"></div>
此外,如果您想停止循环,只需致电clearInterval(intervalId);
我想这就是你要的:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
today = dd + '/' + mm + '/' + yyyy;
var txt = 'welcome to IDM...' + today + "!";
var size = 0, mode = 1, speed = 50;
var intervalId = setInterval(loop, speed);
function loop() {
if (size <= 0) {
mode = +1;
size = 0;
} else if (size >= txt.length - 1) {
mode = -1;
size = txt.length - 1;
}
size += mode;
document.getElementById("demo").innerHTML = txt.substring(0, size);
}
<div id="demo"></div>