我正在尝试运行一个脚本,该脚本将在两次循环调用之间等待1秒。但是代码无法识别i参数。
for (var i = 0; i < lines.length; i++) {
var scanProgressInterval = setInterval(function(i) {
// Process the line, noting it might be incomplete.
if (lines[i].indexOf("(y/n)") > -1) {
console.log("includes (y/n)");
ws.emit('scan', JSON.stringify({scan: false, question: lines[i]}));
}
else if (lines[i].indexOf("any key") > -1) {
console.log("any key");
ws.emit('scan', JSON.stringify({scan: false, key: lines[i]}));
}
}, 1000);
}
此代码有什么问题?
这里“ i”是全局声明的。
尝试将函数用作闭包。
function scanProgressInterval(i){
setInterval(function() {
// Process the line, noting it might be incomplete.
if (lines[i].indexOf("(y/n)") > -1) {
console.log("includes (y/n)");
ws.emit('scan', JSON.stringify({scan: false, question: lines[i]}));
}
else if (lines[i].indexOf("any key") > -1) {
console.log("any key");
ws.emit('scan', JSON.stringify({scan: false, key: lines[i]}));
}
}, 1000);
}
for (var i = 0; i < lines.length; i++) {
scanProgressInterval(i);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句