I can't get this to work. I've been searching online for examples that I could modify, but I am stuck. I don't plan on mastering javascript, so if anyone can provide a simple answer I would appreciate it.
Trying to make this counter count up, and clicking the button will make it slow down the speed at which it counts up...
<html>
<body>
<h2>COUNTUP TOOL</h2>
<button onclick="slow_function()">slow/resume</button>
<label id="seconds">0</label>
<script>
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var interval_between_ticks = 1000;
setInterval(setTime, interval_between_ticks);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = totalSeconds;
}
function slow_function() {
interval_between_ticks = 10000;
}
</script>
</body>
</html>
This doesn't work because the setInterval
function uses the value that was provided at its instantiation. In order to change the interval, you will have to clear the previous interval and set a new one with the new time, something like:
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var interval_between_ticks = 1000;
//Assign the interval to a variable to keep track of it
var interval = setInterval(setTime, interval_between_ticks);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = totalSeconds;
}
function slow_function() {
interval_between_ticks = 10000;
//Clear the old interval so we don't have memory leaks
clearInterval(interval);
//Set the interval with the new time between clicks
interval = setInterval(setTime, interval_between_ticks);
}
<html>
<body>
<h2>COUNTUP TOOL</h2>
<button onclick="slow_function()">slow/resume</button>
<label id="seconds">0</label>
</body>
</html>