i'm trying to make an alarm in JS where i get the value of an input and Multiply it by 1000 to get the ms value and setTimeout a function which changes a paragraph element to become Time Up, the time in the setTimeout is the value of the input x 1000 (because miliseconds) Somewhat like this:
function domChanger() {
document.getElementById("paragraph").innerHTML = "Time Up";
}
function time(alert) {
alert = document.getElementById("input")
alert.value *= 1000;
setTimeout(domChanger(), alert.value)
}
instead of doing the expected for me (doing the function after the time set by alert.value * 1000 has passed) it instantly outputs Time Up. am I misunderstanding anything? because I searched on Google for like 1 hour and I couldn't find anything aside from setTimeout and setInterval.
the problem is
setTimeout(domChanger(), alert.value)
where domChanger() is executed immediatly
you need to pass function reference
setTimeout(domChanger, alert.value)
demo
function domChanger() {
document.getElementById("paragraph").innerHTML = "Time Up";
}
function time() {
var alert = document.getElementById("input")
alert.value *= 1000;
setTimeout(domChanger, alert.value)
}
<p id="paragraph"></p>
<input id="input" type="number" step="1" min="1" value="2">
<button type="button" onclick="time()">time</button>
You don't need to pass the time as parameter. Just do the code bellow.
HTML
<p id="paragraph"></p>
<input type="number" id="input">
<button onclick="time()">Lauch domChanger</button>
<script src="./index.js"></script>
JS
function domChanger() {
document.getElementById("paragraph").innerHTML = "Time Up";
}
function time() {
alert = document.getElementById("input");
alert.value *= 1000;
setTimeout(domChanger, alert.value);;
}