开发者

How to do deferred javascript execution outside of event loop similar to GWT's DeferredCommand

开发者 https://www.devze.com 2023-03-20 21:46 出处:网络
When responding to javascript events sometimes it is advantageous to execute some piece of code once all of the events have been handled, thus not blocking the UI. In GWT this is accomplished th开发者

When responding to javascript events sometimes it is advantageous to execute some piece of code once all of the events have been handled, thus not blocking the UI. In GWT this is accomplished th开发者_如何学编程rough the DeferredCommand. How can I do this with straight Javascript?


setTimeout(f, 1);

where f is the function you want to execute after everything is done. By setting the setTimeout time to 1ms, it will get executed pretty much as soon as the current javascript finishes executing and returns back to the main browser event loop and this event gets to the front of the event queue (there could be other browser events in front of it).


Would any of the implementations of deferred's / promises / futures be what you are looking for?

  • jQuery's is probably the most used now, but not the first.

  • If you're not already using jQuery or if your project is for node.js rather than the browser, the other top contender is probably Q.

(Though indeed both implementations work in both the browser and node.js and they can even be used together.)


Check out Web Workers, I would say more but I haven't tried them out myself.


Does using callback function solve your problem ?

Or

setTimeout(func, 0);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号