Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
How do I add delay within a function in Javascript

I am trying to create a simple function when on click a series of style changes happen to an element.

I want to add a 4-second delay in between the two style changes that I make. I've found a few methods of adding delays before and after a function but not inside a function how can I achieve this?

My Code:

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)"
})

Would really appreciate any advice on this

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can simply use the setTimeout method, it runs a function after the time you set in milliseconds. To achieve what you need, you have to set an anonymous function to it.

More information

Example

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

With your code

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)
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can simply use CSS transition-delay inside that function

about 4 years ago · Juan Pablo Isaza Denunciar

0

Create an anonymous inner function called by 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)
})

Alternately, because this is a CSS transition, you can use CSS transition-delay with this translation.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda