0

I'm trying to use setTimeout.

Without setTimeout my function works,but using setTimeout it stops. Any one knows what I am doing wrong? I want that function works only 3 seconds after click.

let d6
document.getElementById("rollButton").onclick = function d6click(){
d6 = Math.floor(Math.random() * 6) + 1;
document.getElementById("resultd6").innerHTML = d6;
};
setTimeout(d6click, 3000)
  • After clicking the button do you want to update the result with a new random number every three seconds? Is that what the timeout is meant to do? – Andy Sep 25 '22 at 20:30

2 Answers2

0

you need the function declared like this -

function d6click(){
    let d6 = Math.floor(Math.random() * 6) + 1;
    document.getElementById("resultd6").innerHTML = d6;
};
document.getElementById("rollButton").onclick = ()=>{
    setTimeout(d6click, 3000)
};
0

You are setting the callback, but not actually executing the setTimeout function. When you call it, it will begin the timer so you should call it inside the event block

document.getElementById("rollButton").onclick = function d6click(){
    setTimeout(d6timeout, 3000)
};

function d6timeout(){
    let d6 = Math.floor(Math.random() * 6) + 1;
    document.getElementById("resultd6").innerHTML = d6;
}
GreenDiggy
  • 43
  • 1
  • 6