Why is setTimeout executing timeExpired with no delay?
I am learning javascript, and have come across a problem that leaves me completely stumped. When I call setTimeout the function parameter runs immediately with no delay.
Overall program (segment) purpose: User inputs a number of minutes they want to set a timer for. Inputed value is passed to a submitName(), which sets the timer and calls timeExpired() when the timer goes off.
Relevant HTML:
<form id="frm1">
Name: <input type="number" id="fname" name="fname"
step="1" min="1" max="1500" value="1"><br>
</form>
<p>How many minutes do you want to set the alarm for?</p>
<button id="submit" onclick="submitName();">Submit</button>
Relevnt Javascript:
<script>
function timeExpired()
{
document.write("Timer off!");
}
function submitName() {
var x = document.getElementById("fname").value;
var num = x*60000;
document.write("<p id='time'>Timer set for: " + x + " minutes.</p>"
+ "<link rel='stylesheet' href='colours.css'/>");
setTimeout(function(){timeExpired();},num);
}
</script>
What I've tried:
√ Comparing examples on MDN, W3schools, and other questions on stack overflow to try to find a solution.
√ Wrapping in anonymous function (as above). Many variations with and without anonymous function adding/removing the brackets() and semi-colon(); of timeExpired on function call.
√ Debugging with the built in firefox debugger (no errors found).
√ Checking the value submitted by the user is properly assigned to x, and multiple assigned to num.
NOTES:
-I am aware of the dubious reputation of W3schools, and am keeping my eyes open.
-I am aware that document.write() overwrites the contents of the fully-loaded screen. I am only using it in a limited capacity in (user-invoked) pop-up windows.
Without having tried it, I suppose that document.write()
replaces the entire document including the script tag that contains your JavaScript functions. As an effect, the function cannot be executed anymore.
Could you try to replace only the content of an element contained in the body, next to the script tag? For example:
<body> <div id="content"> <form ... <button ... </div> <script> ... </script> </body>