3
For example, below I have two buttons that when clicked display different contents:
let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2");
btn1.onclick = () => {
console.log("BOTÃO 1");
};
btn2.onclick = () => {
console.log("BOTÃO 2");
};
<button id="btn1">Click 1</button>
<button id="btn2">Click 2</button>
But if I want to call the method log()
after a few seconds with the method setTimeout()
passing parameters in the function to be called in the method setTimeout()
, That’s not gonna work:
let btn1 = document.querySelector("#btn1");
let btn2 = document.querySelector("#btn2");
btn1.onclick = () => {
setTimeout(msg("BOTÃO 1"), 1000);
};
btn2.onclick = () => {
setTimeout(msg("BOTÃO 2"), 1000);
};
function msg(txt) {
console.log(txt);
}
<button id="btn1">Click 1</button>
<button id="btn2">Click 2</button>
That’s because I’m calling the job msg()
immediately, because I informed the parentheses. How can I pass parameters to function to be called in the method setTimeout()
?