The problem is with object’s variable:
this.timer
it’s not “global”, so when I click the stop button the value of the variable is wrong.
If I declare a global variable MyObject (loke var mytimer;) and use it instead this.timer, it works.
This is my code:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript" language="JavaScript">
var MyObject = {
init: function(){
this.timer = 0;
document.getElementById("btn1").onclick = function(){
MyObject.RunIt();
};
document.getElementById("btn2").onclick = function(){
clearInterval(this.timer);
};
},
RunIt: function(){
var x=0;
this.timer = setInterval(function(){
x++;
document.getElementById("spn").innerHTML=x;
}, 1000);
}
};
</script>
<style type="text/css">
</style>
</head>
<body onload="MyObject.init();">
<input type="button" id="btn1" value="Run"/>
<input type="button" id="btn2" value="Stop"/>
<span id="spn"></span>
</body>
</html>
The problem is this: when you set “onclick” to a function call like that, there’s no object reference in the call. The browser calls your function to do the “clearInterval”, but “this” is not pointing to your object – in fact, it’s pointing at the button element itself.
Here’s one way to work around the problem:
I know that question-askers on Stackoverflow get annoyed sometimes when people urge them to investigate jQuery or some other modern Javascript framework, but it’s simply a better way to do things.