Exercise Set 5

Exercise 6 of 6

Start an automatic counter when the start button is clicked, and have it stop when the stop button is clicked.

HTML

<button id="startCounterButton">Start counter</button>
<button id="stopCounterButton">Stop counter</button>
<p id="counterParagraph">Counter: 0</p>

JavaScript

var startCounterButton = document.getElementById("startCounterButton");
var stopCounterButton = document.getElementById("stopCounterButton");
var counterParagraph = document.getElementById("counterParagraph");

var counter = 0;
var intervalId = null;

startCounterButton.addEventListener("click", startCounter);
stopCounterButton.addEventListener("click", stopCounter);

function startCounter() {
    // your code will appear here
}

function stopCounter() {
    clearInterval(intervalId);
}

function increaseCounter() {
    counter = counter + 1;
    counterParagraph.innerHTML = "Counter: " + counter;
}

You must be signed in to type your code.

Show your answers to the instructor before moving on.

Last exercise Next topic First exercise