我试图在函数上实现延迟。我应该将函数包含在延迟函数中吗?或者我可以以某种方式添加更多代码,以便动画在页面加载后5秒内不启动?
var typeThis = "blablablabla";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("logoType").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 150);
}
}
document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;
type(typeThis, displayText);

<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>
&#13;
答案 0 :(得分:4)
我认为你要找的是setTimeout
。
window.setTimeout(function () {
type(typeThis, displayText);
}, 5000);
您还可以将其添加到侦听器以了解窗口何时完成加载:
window.addEventListener('load', function () {
window.setTimeout(function () {
type(typeThis, displayText);
}, 5000);
});
一个完整的例子:
var typeThis = "blablablabla";
var displayText = "";
function type(fullString, typedSoFar) {
if (fullString.length != typedSoFar.length) {
typedSoFar = fullString.substring(0, typedSoFar.length + 1);
document.getElementById("logoType").innerText = typedSoFar;
setTimeout(function() {
type(fullString, typedSoFar)
}, 150);
}
}
document.getElementById("logoType").innerHtml = typeThis;
var element = document.createElement('h2');
element.innerHTML = typeThis;
typeThis = element.textContent;
window.addEventListener('load', function() {
window.setTimeout(function() {
type(typeThis, displayText);
}, 5000);
});
&#13;
Waiting 5 seconds...
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>
&#13;
答案 1 :(得分:0)
您最好的选择不是添加更多代码来延迟,而是将其全部包含在超时中:https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
答案 2 :(得分:0)
像这样使用setTimeout()
:
var timeoutID;
function delayedAlert() {
timeoutID = window.setTimeout(slowAlert, 2000);
}
function slowAlert() {
alert("That was really slow!");
}
function clearAlert() {
window.clearTimeout(timeoutID);
}
来源:https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout