2

I would like to write a function that takes a callback and calls it after the function is done.

This is easy:

var callback = function (ref) {
    var i = 1337;
    while (i--) {
        console.log(ref, 'callback');
    }
};

var someFoo = function (ref, callback) {
    console.log(ref, 'self');

    callback(ref);
}

someFoo('one', callback); // 1
someFoo('two', callback); // 2

But here I'm facing this problem: First the someFoo call blocks until the allback is finished. That means this code is equivalent to this (which blocks until each function is finished):

someFoo('one');
callback('one');
someFoo('two');
callback('two');

Now the question: How to make the callback call asynchronous?

4

2 回答 2

9

改变:

callback(ref);

至:

setTimeout(function(){ callback(ref); }, 0);

或者,由于您正在编写 chrome 扩展,因此不必担心旧浏览器,您可以使用bind

setTimeout(callback.bind(null, ref), 0);
于 2013-07-19T15:56:20.867 回答
2

在浏览器中实现的 JavaScript 是单线程的,因此您无法进行真正的异步调用。你可以做的是这样的近似:

setTimeout(function() {
    callback(ref);
}, 1000);

其中 1000 是以毫秒为单位的 1 秒(根据需要进一步延迟)。然而,由于它是单线程的,回调仍然会阻塞其他正在运行的代码。

新的浏览器支持web worker,但是使用 web worker 来近似线程化会给你留下许多旧浏览器无法使用的代码,而且即使是现在也不是所有的新浏览器都支持完整的规范。

于 2013-07-19T15:58:39.537 回答