我正在尝试对函数实现延迟。我应该将函数包装在延迟函数中吗?或者我能以某种方式添加更多代码,以便动画不会在页面加载后 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>
最佳答案
我认为您正在寻找的是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);
});
Waiting 5 seconds...
<a class="navbar-brand" id="topper" href="#"><p id="logoType"></p></a>
关于javascript - 如何在功能上加入延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41268198/