skip to Main Content

I’m creating a program where I basically have this button that I made in CSS, and I want him to (when clicked) flash a color, and then 200ms later, return the color to normal, and for some reason I can’t get it to work right

function highlight_button(button_id){
    button_id.style.backgroundColor="yellow"
    sleep(200)
    button.style.backgroundColor="red"
}

here is the sleep function I used:

function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
        currentDate = Date.now();
    } while (currentDate - date < milliseconds);
}

what I thought would happen was the following:
-the button would appear yellow immediately
-the program would wait 0.2 seconds
-the button would appear red

however…
the following happens:
-the program would wait 0.2 seconds
-the button would appear red

if anyone could help I’d be very much thankfull
it’s my first time working with javascript and I want to get this mistakes out of the way to get better at it

thanks

3

Answers


  1. Chosen as BEST ANSWER
    function highlight_button(button_id){
        button_id.style.backgroundColor="yellow"
    }
    
    highlight_button(id)
    setTimeout(() => button_id.style.backgroundColor="red", 200)
    

  2. use setTimeout(). your code just hangs the browser. or better use CSS transition or animation.

    Login or Signup to reply.
  3. setTimeout(function(){
        //code goes here
    }, 2000); //Time before execution, 1000= 1 sec
    
    or you can use the arrow function too 
    
    setTimeout(() => {
      // Code to be executed after the delay
      console.log('Timeout completed!');
    }, 1000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search