javascript - 如何在功能上加入延迟?

标签 javascript jquery html css

我正在尝试对函数实现延迟。我应该将函数包装在延迟函数中吗?或者我能以某种方式添加更多代码,以便动画不会在页面加载后 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/

相关文章:

javascript - 如何将html标签添加到cytoscape图形节点

javascript - 使用 Cypress 获取在 HTML 文件中分配的对象

javascript - 随机化 float CSS

jquery - 模态内部的 Angular ui-date

javascript - jQuery 验证在有效时启用提交按钮

html - 显示 :none doesn't hide the div content

javascript - 在javascript中使用正则表达式将每个前导和尾随空格替换为下划线

javascript - 将 : Move div up, 悬停在同级之上

java - 如何循环使用JSTL forEach实现自定义结构?

java - 获取当前 &lt;input&gt; 元素的值的最简单/最干净的方法