我是Appcelerator Titanium APP开发的初学者。从this链接的灵感来看,我正在尝试创建一个倒计时器,以便在TableRowView中工作,因为每一行都有自己的时间设置。我自定义这个课程,用分钟和秒钟显示小时。
我在每个TableRowView中创建了以下代码,以便即时执行列表中的倒计时。
代码1
my_timer[timer_index] = new countDown(parseInt(timer_index), parseInt(15), parseInt(50),
function() {
remainingTime.text = ''+my_timer[timer_index].time.h + " : " + my_timer[timer_index].time.m + " : " + my_timer [timer_index].time.s;
}, function() {
//alert("The time is up!");
}
);
my_timer [timer_index ++]启动();
my_time 用于推送每行倒数计时器的所有实例。
数据来自XHR,因此我创建了一个数组文字来保存代码片段中的所有实例。
问题:当我尝试使用此代码运行我的应用时,它向我显示了一个例外情况,例如“time.h
未定义”。但是,我在代码中看到了time.h
。
此外,我可以使用单个数组
将此类用于多个倒计时例如:
my_timer[0] = new countDown(2,5,5,function(){
somelabel1.text = my_timer[0].time.h+":"+my_timer[0].time.m+":"+my_timer[0].time.s;
})
my_timer[1] = new countDown(2,5,5,function(){
somelabel1.text = my_timer[1].time.h+":"+my_timer[1].time.m+":"+my_timer[1].time.s;
})
上面的代码完美无缺,没有错误。但是,如果我尝试在循环中使用此类并传递索引号而不是像代码1 中那样的硬编码值,则会显示异常,如上所述。
任何帮助都会非常明显。
提前谢谢。
答案 0 :(得分:0)
好吧,如果我不得不猜测,我必须猜测,因为你没有给我们一个完整的例子,甚至没有描述你的问题......
直觉就是你在循环中创建行,在嵌套函数中引用可变变量(remainingTime)。但是当你转到循环中的下一个项目时,remainingTime会发生变化。因此,当嵌套函数引用它时,它与您最初指定的不同,因此只有最后一个计时器正在更新。
以下代码对此进行了演示,该代码三次警告“3”。
for (var i = 0; i < 3; i++) {
setTimeout(function() {
alert(i);
}, 100);
}
如果您不知道为什么或如何修复它,那么我建议您花更多的时间来点燃一杯乔和一本关于JavaScript的好书。
答案 1 :(得分:0)
感谢你的时间和答案。我刚刚通过自定义CountDown类
解决了这个问题var countDown = function(h, m, s, _instance_index, fn_tick, fn_end) {
return {
total_sec : h * 60 * 60 + m * 60 + s,
timer : this.timer,
instance_index : _instance_index,
set : function(h, m, s) {
this.total_sec = parseInt(heart) * 60 * 60 + parseInt(e) * 60 + parseInt(s);
this.time = {
h : h,
m : m,
s : s
};
return this;
},
start : function() {
var self = this;
this.timer = setInterval(function() {
///alert('running');
if (self.total_sec) {
self.total_sec--;
var hour = parseInt(self.total_sec / (60 * 60));
var min = (self.total_sec - (parseInt(hour * (60 * 60))) - (self.total_sec % 60)) / 60;
self.time = {
h : parseInt(self.total_sec / (60 * 60)),
m : parseInt(min),
s : (self.total_sec % 60)
};
fn_tick(self.time.h + ":" + self.time.m + ":" + self.time.s, self.instance_index);
} else {
self.stop();
fn_end();
}
}, 1000);
return this;
},
stop : function() {
clearInterval(this.timer);
this.time = {
h : 0,
m : 0,
s : 0
};
this.total_sec = 0;
return this;
}
};
};
使用以下代码调用此类:
my_timer[items_json.Record.NEW[i].ASSIGN_QUEST_ID] = new countDown(parseInt(n[0]), parseInt(n[1]), parseInt(n[2]), items_json.Record.NEW[i].ASSIGN_QUEST_ID, function(curr_time, instance_index) {
questTime[instance_index].text = 'TIME LEFT ' + curr_time;
}, function() {
//alert("The time is up!");
});
my_timer[items_json.Record.NEW[i].ASSIGN_QUEST_ID].start();