0

I am trying do a CSS change via JavaScript. I have a quiz site where, when the user marks the correct option, the option will become green, and when the user marks the incorrect option, the option will become red, but I have to change the color and redirect the user for another page, but the CSS change is very slow and, at certain times, doesn't work. This is my code:

CSS:

.choice{
  white-space: normal;
  word-wrap: break-word;
  margin: 20px;
  width: calc(40% + 100px);
  height: calc(10% + 10px);
  border-style: solid;
  border-color: rgba(0, 0, 0, 0.4);
  border-radius: 7px;
  background-color: rgba(255,255,255,0.6);
  cursor: pointer;
  font-size: 20px;
  transition: 0.4s;
}

JS:

function sleep(ms) {
    var d = new Date();
    var d2 = null;
    do { d2 = new Date(); }
    while(d2-d < ms);
}

function govariable(page,variable,valor,id,color) {
    document.getElementById(id).style.backgroundColor = color
    sleep(3000)
    window.location.replace(`${page}?${variable}=${valor}`)
}
1
  • 1
    I suggest removing the sleep function since it blocks the whole page/script from running. You can use setInterval() to wait three seconds before leaving the page. Commented Nov 15, 2019 at 17:44

1 Answer 1

1

When you change something in the DOM (in this case, your background color) JavaScript won't update your screen until the event it is processing has finished.

This is because JavaScript runs in only one thread - it can't be looping around and around and re-displaying your background colour at the same time! It needs to finish looping first.

Instead of trying to implement a "sleep" function that will never work well in a single-threaded javascript world, you should try using setTimeout().

function govariable(page,variable,valor,id,color) {
    document.getElementById(id).style.backgroundColor = color
    setTimeout(function() {
        window.location.replace(`${page}?${variable}=${valor}`)
    }, 3000);
}

Instead of looping around again and again until time is up, at a very simplistic level this does something more like setting an internal "wake-up alarm" inside the JavaScript engine, that in 3000 milliseconds will go off, and tell JavaScript to run the code inside it. In this case, to call window.location.redirect.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now my code is working, i will finish the topic, :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.