- What is event loop ?
- Why
shouldmust we know event loop ?
Event loop is what allows js application to work with asynchronous operations (setTimeout, AJAX, ...).
Browser under the hood has:
- Call stack.
- Event loop & event (or callback) queue.
- Js Heap.
- Web APIs.
When call stack has function that uses web apis with callback, it registers callback to the web api and moves to the next function.
Then the api will send callback to callback queue if something happens.
For app that needs real time data and has a lot of user's interactions, knowing event-loop will help us understand and avoid regular bugs:
- Warning: setState(…): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.
- The wrong data being used.
- Memory leaks.
class OrderBook extends Component {
componentDidMount() {
this.subscribe();
}
subscribe() {
if (this.unsubscribe) {
this.unsubscribe();
}
getOrderBook(this.props.productId)
.then((data) => {
this.setState({
orderBookData: data,
});
subscribe(this.props.productId, this.onSubscribe)
.then((unsubscribe) => {
this.unsubscribe = unsubscribe;
});
});
}
onSubscribe(data) {
this.setState({
orderBookData: data,
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.productId !== this.props.productId) {
this.subscribe();
}
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
}
- https://www.youtube.com/watch?v=8aGhZQkoFbQ
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
- https://itnext.io/how-javascript-works-in-browser-and-node-ab7d0d09ac2f