如何在 Javascript 中的函数内添加延迟

How do I add delay within a function in Javascript

我正在尝试创建一个简单的函数,当单击元素时会发生一系列样式更改。

我想在我所做的两次样式更改之间添加 4 秒的延迟。我发现了一些在函数之前和之后添加延迟但不是在函数内部添加延迟的方法,我该如何实现?

我的代码:

const btnEl = document.getElementById("btnel")
const subtl = document.getElementById("chp1sub")

document.getElementById("chp1sub").style.backgroundColor = "red";

btnEl.addEventListener("click", function(){
    subtl.style.backgroundColor = "blue"
    
// 4 second delay here before running next line

    subtl.style.transform = "translateY(-90px)"
})

非常感谢对此的任何建议

您可以简单地使用 setTimeout 方法,它会在您设置的毫秒数后运行一个函数。为了实现你所需要的,你必须给它设置一个匿名函数。

More information

例子

setTimeout(() => {
  /* Code to run after 4 seconds */
}, 4000)

用你的代码

const btnEl = document.getElementById("btnel")
const subtl = document.getElementById("chp1sub")

document.getElementById("chp1sub").style.backgroundColor = "red";

btnEl.addEventListener("click", function(){
  subtl.style.backgroundColor = "blue"
    
  setTimeout(() => {
    // 4 second delay here before running next line
    subtl.style.transform = "translateY(-90px)"
  }, 4000)
})

创建一个由 setTimeout

调用的匿名内部函数
const btnEl = document.getElementById("btnel")
const subtl = document.getElementById("chp1sub")

document.getElementById("chp1sub").style.backgroundColor = "red";

btnEl.addEventListener("click", function(){
    subtl.style.backgroundColor = "blue"
    
    setTimeout(function(){
        subtl.style.transform = "translateY(-90px)"
    },4000)
})

或者,因为这是一个 CSS 转换,您可以将 CSS transition-delay 用于此翻译。

您可以在该函数中简单地使用 CSS transition-delay