Reputation: 663
I found this interval function and I have been using it on my website. However, i need to get the total duration from the interval. I tried modifying it so i could call timer.total_duration to get the total amount of time but when i try running the modified code i get an error saying "Uncaught TypeError: number is not a function" the modified function is:
function interval(duration, fn) {
this.baseline = undefined
this.total_duration = 0.0
this.run = function () {
if (this.baseline === undefined) {
this.baseline = new Date().getTime()
}
fn()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
if (nextTick < 0) {
nextTick = 0
}
this.total_duration += nextTick //line giving the error
(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
}
this.stop = function () {
clearTimeout(this.timer)
}
}
Any idea why I'm getting this error, and how to fix it so I can get the total duration?
Upvotes: 0
Views: 72
Reputation: 187034
Semicolons! They are not optional!
If you dont put them in, the interpreter puts them in for you. Or in some cases fails to put them in where you would expect.
this code:
this.total_duration += nextTick //line giving the error
(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
is being parsed as if was this code:
this.total_duration += nextTick(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
nextTick
is a number, and not a function, so it obviously can't be invoked.
You want this:
this.total_duration += nextTick; // <-- the semicolon that fixes your stuff
(function (i) {
i.timer = setTimeout(function () {
i.run(end); // <-- semicolon! end of statement
}, nextTick); // <-- semicolon! end of setTimeout()
}(this)); // <-- semicolon! end of anonymous function invocation
You would do well to add semicolons at the end of every single statement. Your future debuggers will thank you.
Upvotes: 2