Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading