异步JS问题 - 变量范围或其他错误?

时间:2012-09-30 23:07:49

标签: javascript asynchronous

我在select元素的change事件上有一个监听器:在更改时,提取文件并计算复杂的SVG并加载到DOM(读取:需要相当多的CPU周期) )。问题是,如果您非常快速地更改select(通过编码键盘快捷键),则会将多个内容加载到SVG容器中 - 我只想一次加载一个。为了解决这个问题,我做了这个(半伪):

select.on("change", function() { queue(this.val); });

var queuedFile, state = "ready";
function queue(file) {
    queuedFile = file;
    // NB: in real code, queuedFile is a property and the getter empties the queue
    if (state === "ready") { loadFile(queuedFile); }
}

function loadFile(file) {
    state = "busy";

    ajaxGet(file, function(result) {

        // lots of statements, iterators, calls to other fns

        state = "ready";
        // NB: again in real code the getter empties the queue
        var qf = queuedFile;
        if (qf) { clearSVG(); loadFile(qf); }

    }); // end ajaxGet
}

也就是说:在select更改时,对新文件进行排队,如果文件加载器没有忙于加载另一个文件,则加载它,否则什么都不做。文件加载器完成后,如果有排队文件,请清除SVG并加载排队文件。看起来这应该只允许一次在SVG容器中的一个文件。

实际上,state"busy"中签入时永远不会queue(),因此我仍然会将多个文件加载到SVG。 console.log(state)之后state = "busy"显示"busy"。我在这里错过了什么?我不认为这是queuedFile范围的问题。


为了完整性,我的队列属性是:

// given: all of this code is enclosed in a function that returns an object "viewer".
// (only one instance of the "viewer" is created)

Object.defineProperty(viewer, "queuedFile", {
    get: function () {
        console.log("dequeuing", this.filequeue);
        var buffer = this.filequeue;
        this.filequeue = null;
        return buffer;
    },
    set: function (newval) {
        console.log("queuing", newval);
        this.filequeue = newval;
    }
});

1 个答案:

答案 0 :(得分:0)

根据评论,这似乎对你有帮助!

http://jsfiddle.net/2FNsh/1/

你的叉子最终有所帮助:

http://jsfiddle.net/FkMHw/1/