So I am trying to use setTimeout on one of the functions triggered by a button, but no matter how I format it or where I put it, it just doesn’t work.
On the website, there is a magic 8 ball a user would click, the animation would play, and then 3 seconds later (that’s how long the animation is) a popup with an answer would appear. Everything works except the delay for a popup to appear. No matter if I use the setTimeout function or not, the popup appears right away after clicking the button. Is there something I am missing or doing wrong?
Any help would be appreciated!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Magic 8 Ball</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<h1>Magic 8 Ball</h1>
<p>Ask a question and click on the Magic 8 Ball to reveal the answer</p>
<div class = "8ball">
<button id = "8bbtn" onclick="spin(); show()">
<video id="video1" width="800">
<source src="./media/8ball.mp4" type="video/mp4">
</video>
</button>
</div>
<div id = 'splashscrn'>
<h1>THE ANSWER</h1>
</div>
<script>
var myVideo = document.getElementById("video1");
var popup = document.getElementById("splashscrn");
function spin() {
myVideo.play();
}
function show() {
popup.style.display = 'block';
setTimeout(show, 3000);
}
</script>
</body>
</html>
2
Answers
You are calling both
spin
andshow
here:onclick="spin(); show()"
. So the popup is shown immediately. ThesetTimeout
function call insideshow
is callingshow
again after 3 seconds, which visibly does nothing (since the popup is already shown by the call before).I would suggest to remove
show()
from the onclick handler and instead move thesetTimeout
function at the end of yourspin
function.I hope I understood correctly. Your only problem is
setTimeout
not working?The first thing I noticed was that you closed an additional element of the button:
And as for your question, you should call
setTimeOut
outside the function and then call your function inside it. It’s like calling a function after the job is done. But you call it insetTimeOut
because you need time.I hope this answer helped you.