在javascript中修改计时器间隔函数以给出总持续时间时遇到问题
我发现了这个,我一直在我的网站上使用它。但是,我需要从间隔中获取总持续时间。我试图修改它,以便调用timer.total_duration来获取总时间,但当我尝试运行修改后的代码时,我收到一个错误,错误是“Uncaught TypeError:number不是函数”,修改后的函数是:在javascript中修改计时器间隔函数以给出总持续时间时遇到问题,javascript,Javascript,我发现了这个,我一直在我的网站上使用它。但是,我需要从间隔中获取总持续时间。我试图修改它,以便调用timer.total_duration来获取总时间,但当我尝试运行修改后的代码时,我收到一个错误,错误是“Uncaught TypeError:number不是函数”,修改后的函数是: function interval(duration, fn) { this.baseline = undefined this.total_duration = 0.0 this.run
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)
}
}
功能间隔(持续时间,fn){
this.baseline=未定义
此项。总持续时间=0.0
this.run=函数(){
if(this.baseline==未定义){
this.baseline=new Date().getTime()
}
fn()
var end=new Date().getTime()
此值为0.baseline+=持续时间
var nextTick=duration-(end-this.baseline)
if(nextTick<0){
nextTick=0
}
this.total_duration+=nextTick//给出错误的行
(职能(一){
i、 定时器=设置超时(函数(){
i、 运行(结束)
},nextTick)
}(本节)
}
this.stop=函数(){
clearTimeout(this.timer)
}
}
你知道我为什么会出现这个错误,以及如何修复它以获得总持续时间吗?分号!它们不是可选的 如果你不把它们放进去,翻译会替你放进去。或者在某些情况下,无法将它们放在您期望的位置 此代码:
this.total_duration += nextTick //line giving the error
(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
this.total_duration += nextTick(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
正在进行分析,就像此代码一样:
this.total_duration += nextTick //line giving the error
(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
this.total_duration += nextTick(function (i) {
i.timer = setTimeout(function () {
i.run(end)
}, nextTick)
}(this))
nextTick
是一个数字,而不是一个函数,因此它显然不能被调用
你想要这个:
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
this.total_duration+=nextTick;//我自己也在看这个问题。很好的发现:-)作为原始提问者的额外提示,JSLint是一个很好的工具,可用于查找缺少的分号和代码中的其他潜在问题。谢谢,这很有效。从现在起我会记得用分号。