简体   繁体   中英

random number javascript onclick doesn't work

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)

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)
};

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(d6click, 3000)
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM