|Written by Ian Elliot|
|Sunday, 26 November 2017|
Page 2 of 2
Although it isn’t part of the standard, some browsers have implemented a maximum number of microtasks that will be serviced in one go. This does free the UI every now and again, but you will still find it difficult to do anything.
Obviously generating 10,000 thens isn’t a very good idea and this sort of problem is unlikely to actually occur in practice. If it does you need to rethink the way you are doing the job. The problem is that there are other ways that the same thing can occur – chained Promises and combined Promises using all, say, can all add multiple microtasks to the queue that keep the UI thread busy without an opportunity to service tasks. It is important to know that breaking up a process into multiple microtasks does not keep the UI responsive.
Node.js setImmediate & nextTick
Node.js has two useful functions which can create tasks and microtasks.
The setImmediate function will queue a task just like setTimeout, but without any timing restrictions. It has been implemented in Edge and IE 10 and later, but it has been removed from Chrome, Firefox and Safari.
adds the function to the task queue and it will be executed as fast as possible, but after any microtasks.
Where it is supported it is faster than postMessage as a way of queuing a task, but it is only safe to use in Node.js.
As well as a task queue, Node.js has a microtask queue that is used for the same things as in a modern browser. In addition it has the process.nextTick function which can be used to queue a microtask:
In the case of node.js you can also use the process.maxTickDepth to set the number of consecutive microtasks that will be processed before a task is.
There is no support for nextTick in any browser, but:
does the same job.
What have we learned?
Now Available as a Print Book:
You can buy it from: Amazon
or email your comment to: email@example.com
|Last Updated ( Monday, 27 November 2017 )|