【发布时间】:2016-08-02 11:03:34
【问题描述】:
我似乎遇到了一个我似乎无法弄清楚的非常简单的错误。我有两个功能。一个允许通过数组进行定时迭代(慢迭代),另一个只将数组中的项目组合成一个句子(testfunction)。我希望在 while 循环中调用这两个函数,以便 while 循环将在一天中的时间之间不断运行(这是 Now_time 变量)。
如果我在没有 while 循环的情况下运行代码,它会正确运行。一旦我引入 while 循环,它只会迭代第一个元素,而不是使用函数连续遍历数组。
有什么建议吗?
//Sample array
var data = [
{Name:"Cape Town",City_Type:"Seaside"}
,
{Name:"Johannesburg",City_Type:"Inland"}
,
{Name:"Durban",City_Type:"Seaside"}
,
{Name:"Bloemfontein",City_Type:"Inland"}
];
// Slowly iterates through a given array
function slowArrayIterate(array, iterateFunc, start, speed) {
iterateFunc(array[start], start, array);
if (typeof array[start + 1] !== 'undefined') {
setTimeout(function() {
slowArrayIterate(array, iterateFunc, start + 1, speed, done);
}, speed);
} else {
done();
}
}
// Forms the sentence from the elements in the array
function testfunction(a,b){
var complete = a +" is a " + b +" city.";
console.log(complete);
}
// Gets the time of the day
var myDate = new Date(Date.now());
var time_now = myDate.toString().substring(16,24);
var here = time_now;
var there = time_now;
var everywhere = time_now;
var now = here.substring(0,2)+ there.substring(3,5) + here.substring(6,8);
var Now_time = parseFloat(now);
while (Now_time >= 73000 || Now_time <=170000) {
console.log("working");
// Calls the fucntion to slowly iterate
slowArrayIterate(data, function(arrayItem) {
console.log(arrayItem.Name);
console.log(arrayItem.City_Type);
// Calls the fucntion to form a sentence on the console log
testfunction(arrayItem.Name , arrayItem.City_Type);
}, 0, 1000);
// refreshes the time to see if it should still be running
myDate = new Date(Date.now());
var time_now = myDate.toString().substring(16,24);
var here = time_now;
var there = time_now;
var everywhere = time_now;
var now = here.substring(0,2)+ there.substring(3,5) + here.substring(6,8);
var Now_time = parseFloat(now);
console.log(Now_time);
}
【问题讨论】:
-
在所有变量上创建一个闭包 ....点击链接,您的问题将得到解决stackoverflow.com/questions/17491718/…
-
感谢苏拉吉的反馈。我尝试查看建议的链接并应用解决方案,但遇到了错误。
标签: javascript loops while-loop