user10102839
user10102839

Reputation:

How can I delay the output of a button in javascript

I am working on a button where you click it and a random number 1-50 appears. But once I got into it, I realized it was kind of boring so I am going to add a noise that plays for around 10 seconds and then the number appears. But the problem is that now that I tried to add the delay to the button it does not put the output number.

Here is my code (Dont mind the part about where the button is disabled because that is just to stop the cheating. There are other parts to this. This is just the code for this part I need help with):

<button id="rnum" 
        onclick="numFunction();setTimeout(delayFunction, 10500);" 
        disabled>
    Random Number
</button>

<p id="randnum"></p>

<script>
    function delayFunction()
    function numFunction() {
        var x = Math.floor((Math.random() * 50) + 1);
        document.getElementById("randnum").innerHTML = x;
    }
</script>

Upvotes: 0

Views: 75

Answers (2)

pr0p
pr0p

Reputation: 2358

function delayFunction(callback){
  setTimeout(callback, 2000)
}

function numFunction() {
    var x = Math.floor((Math.random() * 50) + 1);
    document.getElementById("randnum").innerHTML = x;
}
<button id="rnum" 
        onclick="delayFunction(numFunction)">
Random Number
</button>

<p id="randnum"></p>

Upvotes: 0

Kyy13
Kyy13

Reputation: 315

Random Number

          <p id="randnum"></p>

          <script>
          function numFunction() {
             setTimeout(function(){
              var x = Math.floor((Math.random() * 50) + 1);
              document.getElementById("randnum").innerHTML = x;
             }, 10500);
          }
          </script>

Upvotes: 2

Related Questions