Search code examples
javascriptbuttondelay

How do i delay a function until a button is pressed?


Okay, so I have this quiz, where you press buttons which changes a variables value. The value you are left with in the end will determine your result. This is how it find out the result:

function check() {

 if(poeng >= 500) {

   document.write('<img style="position: relative; top: 500px; left: 200px;" src="bilder/cat2.jpg">');
 }

The problem is, is that one of the first buttons changes the variable to a value over 500- i want to be able to go through all the questions in the quiz before getting thue result. Is it possible to make it so that the function written over there will be delayed until i press the last button? (Sorry if this is confusing)


Solution

  • If you have your poeng variable global, then you can add event listeners to your quiz buttons. These will be fired when clicked and check if your condition is true (poeng >= 500 in your case). Otherwise, you will have to pass the parameter to the check functiion.

    button.addEventListener("click",check)
    
    function check() {
     if(poeng >= 500) {
       document.write('<img style="position: relative; top: 500px; left: 200px;" src="bilder/cat2.jpg">')
     };
     }
    
    button.addEventListener("click",check(poeng))
    
    function check(poeng) {
     if(poeng >= 500) {
       document.write('<img style="position: relative; top: 500px; left: 200px;" src="bilder/cat2.jpg">')
     };
     }
    

    Hope I helped!