Reputation: 15
I'm working on an application that will allow me to click a button on the web page and then start my timer object. However, the timer will not start onclick
.
<script type="text/javascript">
var Timer = function()
{
// Property: Frequency of elapse event of the timer in millisecond
this.Interval = 1000;
// Property: Whether the timer is enable or not
this.Enable = new Boolean(false);
// Event: Timer tick
this.Tick;
// Member variable: Hold interval id of the timer
var timerId = 0;
// Member variable: Hold instance of this class
var thisObject;
// Function: Start the timer
this.Start = function()
{
this.Enable = new Boolean(true);
thisObject = this;
if (thisObject.Enable)
{
thisObject.timerId = setInterval(
function()
{
thisObject.Tick();
}, thisObject.Interval);
}
};
// Function: Stops the timer
this.Stop = function(){
thisObject.Enable = new Boolean(false);
clearInterval(thisObject.timerId);
};
};
//counts down the timer
function timer_tick()
{
index = index - 1;
document.getElementById("blue").innerHTML =index;
if (index === 0)
{
obj.Stop();
}
}
If I remove function startBlue()
but leave the code inside of it, the timer will run on page load. So after looking at my code I think the issue is where I call startBlue
(below in the html) or somewhere in this function:
function startBlue(){
var index = 300;
var obj = new Timer();
obj.Interval = 1000;
obj.Tick = timer_tick();
obj.Start();
}
</script>
<body>
<div id ="Objectives">
Your Objectives:
<br>
<br>
<label>Blue Buff:</label>
<button id="yosb" onclick ="startBlue();">Start Blue</button>
<h2 id = "blue">
</h2>
</div>
</html>
Upvotes: 1
Views: 127
Reputation: 348
Your problem isn't the space, it is a scope and reference issue.
var index, obj; //define index and obj outside of startBlue().
function startBlue(){
index = 300; //initialize without redefining (remove 'var').
obj = new Timer(); //initialize without redefining (remove 'var').
obj.Interval = 1000;
obj.Tick = timer_tick; // store the actual function in obj.Tick, not the return (remove the '()' from the end of timer_tick)
obj.Start();
}
If you define a variable inside of a function, then that variable is only accessible inside the scope of that function only. By defining it outside, you allow that variable to be accessed from the outer scope.
To store functions in variables, you must be sure not to include the parens at the end of the function name. Otherwise the function will be executed first, and the return value will then be stored in the variable instead of the function it self.
Upvotes: 3
Reputation: 1129
The following line
<button id="yosb" onclick ="startBlue();">Start Blue</button>
Should be changed to
<button id="yosb" onclick="startBlue();">Start Blue</button>
You are adding an unnecessary space between the onclick and the =.
Upvotes: 0