Q:

How to stop a time function nested in a function?

I was able to get the following code from some class work I'm working on. It works really well for what I need it for and I like that I can call startTime(); to start it. However, I'm now at a point where I need to figure out how to stop it.  Is there a way to do startTime(stop); or something similar? 
function startTime() {
    let hours = 0;
    let minutes = 0;
    let seconds = 0;
    const timer = setInterval(function () {
        seconds++;
        if (seconds === 60) {
            minutes++;
            seconds = 0;
        }
        second.innerHTML = formatTime();
    }, 1000);
    function formatTime() {
        let sec = seconds > 9 ? String(seconds) : '0' + String(seconds);
        let min = seconds > 9 ? String(minutes) : '0' + String(minutes);
        return min + ':' + sec;
    }
}

A:

You need to scope the variable that the setInterval is assigned to outside of startTime, so that it can be accessed and have clearInterval called on it externally. For example, this snippet will assign an interval to the timer, and then clear the interval after 5 seconds:

let timer;
function startTime() {
    let hours = 0;
    let minutes = 0;
    let seconds = 0;
    timer = setInterval(function () {
        seconds++;
        if (seconds === 60) {
            minutes++;
            seconds = 0;
        }
        second.innerHTML = formatTime();
    }, 1000);
    function formatTime() {
        let sec = seconds > 9 ? String(seconds) : '0' + String(seconds);
        let min = seconds > 9 ? String(minutes) : '0' + String(minutes);
        return min + ':' + sec;
    }
}
function stopTime() {
  clearInterval(timer);
}
startTime();
setTimeout(stopTime, 5000);
<div id="second"></div>

