我试图用setTimeout
执行一些语句,这实际上是在getSendingJSON("/plot",args,plotReglaFalsa)
问题与回调
这是回调函数执行plotReglaFalsa
内执行的函数内部setTimeout函数的变量是代码段的句子被执行通过setTimeout
:
for (series in respuesta) {
if (series != "x" && series != "y" && series != "raiz") {
setTimeout(function(respuesta,series){plot.highlight(c,[respuesta[series].a,0])},1500)
setTimeout(function(respuesta,series){plot.highlight(c,[respuesta[series].b,0])},1800)
c++
}
}
这里的问题是,respuesta等系列实际上是现有一旦回调发生。
当我尝试运行我得到以下控制台输出:
TypeError: series is undefined ...Timeout(function(respuesta,series){plot.highlight(c,[respuesta[series].a,0])},15... 16 biseccion.js (line 50) TypeError: series is undefined ...Timeout(function(respuesta,series){plot.highlight(c,[respuesta[series].b,0])},18...
这是我的全部代码:
function plotReglaFalsa(respuesta) {
var result = []
result.push({
label: "fx",
color: "red",
data: _.zip(respuesta['x'], respuesta['y'])
})
for (series in respuesta) {
if (series != "x" && series != "y" && series != "raiz") {
result.push({
color: "blue",
data: [[]]
})
}
}
var plot = $.plot( $("#placeholder"),
result,
{ selection:{mode: "xy"},
zoom: { interactive: true },
pan: { interactive: true },
grid: { markings: [{ xaxis: { from: 0.0, to: 0.0 }, color: 'black', lineWidth: 2 }, { yaxis: { from: 0.0, to: 0.0 }, color: 'black', lineWidth: 2 }] }
})
plot.getOptions().selection.mode = null
var c = 1
for (series in respuesta) {
if (series != "x" && series != "y" && series != "raiz") {
setTimeout(function(respuesta,series){plot.highlight(c,[respuesta[series].a,0])},1500)
setTimeout(function(respuesta,series){plot.highlight(c,[respuesta[series].b,0])},1800)
c++
}
}
}
getSendingJSON("/plot",args,plotReglaFalsa)
function resaltarPuntos(plot,respuesta,series,c,x){
plot.highlight(c,[respuesta[series].x,0])
}
function desResaltarPuntos(plot){
plot.unhighlight()
}
getSendingJSON
实际上是AJAX。我怎样才能完成这项工作?
可能重复[臭名昭著的Javascript循环问题?(http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue) – elclanrs
你传递你的函数'的setTimeout()' ,所以'setTimeout()'会调用它们。然而,他们不知道你想要的变量是什么,所以他们没有办法将它们传递给函数。定义函数参数并不会以某种方式导致它们被传递给函数。 –
[JSHint](http://jshint.com)会给你一些警告 - “不要在循环中创建函数” – elclanrs