Skip to content
Sign upLog in
← Back to Community

HTML onclick a function within a function

Profile icon
[deleted]

This will (probably) be the last question for this repl. Anyway, I am making a repl that keeps track of how much time you spend on your computer. And Here is the problem:
When The user is done using the computer, they click the stop button. But the stop function is INSIDE the

poop() //I dont know why I named it poop.

function. And it raises an error where its not defined. But If I put it outside the function, the variable

var time = setInterval(() => { poop(); }, 1000); // on line 28, used on line 47 to stop the stopwatch

is not defined, so what do I do?

Comments
hotnewtop
Profile icon
kanepequie

Your post was quite beneficial to me, and I look forward to reading more of your work in the future. I've also just found a fun game called five nights at freddy's that you may join and play with me if you have some extra time.

Profile icon
Coder100

Hi! That is becuase of scope

right now the stop() function is inside of the poop() (haha) function so that means only the poop() code can access it. Instead have your code like this:

function time() { function poop() { /* ... */ } } function stop() { // now the function can be accessed! }
Profile icon
mwilki7

Why are there functions defined inside other functions?

function time() { var time = setInterval(() => { poop(); }, 1000); function poop() { sec = sec + 1; if (sec == 60) { sec = 0; min = min + 1; } if (min == 60) { min = 0; hour = hour + 1; } document.getElementById("sec").innerHTML = "Seconds:" + sec; document.getElementById("min").innerHTML = "Minutes:" + min; document.getElementById("hour").innerHTML = "Hours:" + hour; } function stop() { clearInterval(time); } }

I think these should be separated, and maybe rename the var time variable just in case there are name collisions.

var time_intervalID = undefined; function time() { time_intervalID = setInterval(() => { poop(); }, 1000); } function poop() { sec = sec + 1; if (sec == 60) { sec = 0; min = min + 1; } if (min == 60) { min = 0; hour = hour + 1; } document.getElementById("sec").innerHTML = "Seconds:" + sec; document.getElementById("min").innerHTML = "Minutes:" + min; document.getElementById("hour").innerHTML = "Hours:" + hour; } function stop() { clearInterval(time_intervalID); }