Below is a simple code snippet that I wrote:
- HTML & CSS:
<!DOCTYPE html>
<html>
<head>
<title> JavaScript Console </title>
<style>
button { text-align:center;
width:200px;
height:30px;
font-size:17px;
font-family:courier new;
border:solid 2px black;
font-weight: bold;
background-color:lightblue;
cursor:pointer;
border-radius: 20px;
transition: 0.5s;
}
button:hover {
transform: scale(1.2, 1.2);
font-size:19px;
background-color: cyan;
}
</style>
</head>
<body style="text-align:center">
<fieldset>
<legend style="text-align:center;margin-bottom: -20px"><h1 id="h1" style="text-align:center;">JavaScript tests on console</h1></legend>
<p style="color:green;"> Have fun coding !</p>
<br/>
<div style="text-align: center;"><button id="btn" onClick="buttonHandler()" >Show time</button></div>
<p id="time" style="color:blue;"></p>
<p id="tick" style="color:red;"></p>
<p></p>
</fieldset>
<script src="./test.js"></script>
</body>
</html>
- JavaScript:
console.log('Console is working fine !');
/**********************************************************************/
var x = 60;
function tick() {
var date = new Date();
document.getElementById("time").innerHTML = date;
x--;
document.getElementById('tick').innerHTML = `The time will be hidden after ${x} seconds`;
}
function clearAll(id) {
window.clearInterval(id);
document.getElementById('time').style.display = "none";
document.getElementById('tick').style.display = "none";
}
function buttonHandler(e) {
var id = window.setInterval(tick,1000);
setTimeout(()=> clearAll(id),60000);
}
/**********************************************************************/
The issue I'm facing is that the 'Show time' button only works for the first click and doesn't work again after that.
I believe the problem lies with the setInterval() method which runs only once, but I'm not sure how to resolve it.
Could someone provide guidance on how to fix this issue?