I declared a function containing setInterval and a function containing clearInterval outside of window.onload = function(){...} . However the timer cannot be stopped as expected
When I clicked the start button, I can see the timer start correctly and "hello" is being printed in the consoled repetitively. However, when I clicked the "stop" button, the timer won't be cleared.
I think upon loading of the document, the onclick function for "start_btn" and "stop_btn" should be ready, then I use the start button and it will set the variable "timer" to a number, and later I click the stop button, why it cannot see the current non-null "timer" variable?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
*{
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var timer = null;
var start_btn = document.getElementById("start");
var stop_btn = document.getElementById("stop");
startFunc(start_btn, timer);
stopFunc(stop_btn, timer);
};
function startFunc(target, timer){
target.onclick = function(){
timer = setInterval(function(){
console.log("hello");
}, 300);
};
}
function stopFunc(target, timer){
target.onclick = function(){
clearInterval(timer);
};
}
</script>
</head>
<body>
<button type="button" id="start">start</button>
<button type="button" id="stop">stop</button>
</body>
</html>
startFuncis only modifying the local copy oftimer. Consider widening its scope or passing around an object so that it can be mutated when passed as an argument. - CollinD