- Using Event Emitters
- Using event.addListener and event.on
- Using once()
- Using setTimeout()
- Using setInterval()
- Using setImmediate()
- Partitioning Long-running Tasks
- Conclusion
Partitioning Long-running Tasks
Any code that is a long-running operation will make the UI unresponsive, especially with single-threaded JavaScript applications. An example is a For loop with many iterations that makes the application lag. A solution to this problem is to use the setImmediate() method on your long operations.
An example of using setImmediate() to split up (partition) a long-running piece of code appears below:
var i = 0; function longRunningOperation() { if (i < 1000000000) { console.log("Hello from iteration " + i); i++; setImmediate(longRunningOperation); } } longRunningOperation();
In the example, a single iteration is processed while longRunningOperation() is invoked. The operation allows other code to run while executing longRunningOperation().