I'm trying to create a self contained timer where all variables are inside a object.
For the most part it works but I can get this to fire once. What am I missing?
function Countdown()
{
this.appId = null;
this.timerId = null;
this.seconds = null;
this.decrementCounter = function (instant)
{
if (instant == null)
return;
instant.tick();
if (instant.seconds === 0)
{
instant.tickEnd();
instant.stop();
}
instant.seconds--;
};
this.tick = function ()
{
var xx = this.appId
};
this.tickEnd = function ()
{
var xx = this.appId
};
this.start = function ()
{
clearInterval(this.timerId);
this.timerId = setInterval(this.decrementCounter(this), 1000);
};
this.stop = function ()
{
clearInterval(this.timerId);
};
}
You are calling the function, not assigning a reference
Seems weird you are passing in "this" as an argument...
use bind()
or a closure
I provided an answer to another question that creates a simple stopwatch.
You could modify the code slightly to count down instead of up.
Here's a jsbin demo.
Original snippet
In the following bit of code:
You are executing this immediately:
And so the return value of that, is what is being called by setInterval each second. Usually you would want to pass a function closure, like this:
Then, when your timer is executed, it's the function which is called, and that function then executes what you want. The other option is to pass the first parameter as a string such as "callAFunction('blah')" which will be evaluated each second and executed, but I believe the above is that you want.
I modified your code a bit and changed the line containing
setInterval
to this:The functions run inside of
setInterval
run in thewindow
scope. It only runs once, because you don't pass the function itself just the result of it. You need to return the actual function or pass an anonymous function which calls it.jsfiddle demo: http://jsfiddle.net/2gLdL/1/
Try this: