Skip to content

Latest commit

 

History

History
85 lines (81 loc) · 2.54 KB

PITCHME.md

File metadata and controls

85 lines (81 loc) · 2.54 KB

Event Loop


Menu

  • What is event loop ?
  • Why should must we know event loop ?

What is 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.

eventLoop

callStack

Async operations

eventLoop

Async operations

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.

When the stack is empty, event loop moves the callback from callback queue to stack.

Why should must we know event loop ?

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();
    }
  }
}

Solution

References


Thanks !