Giter Site home page Giter Site logo

time-slicing's Introduction

time-slicing

Break down long tasks into smaller tasks, avoid blocking the main process.

Introduce

Usually synchronous code execution for more than 50 milliseconds is a long task.

Long tasks will block the main thread, causing the page to jam, We have two solutions, Web worker and Time slicing.

We should use web workers as much as possible, but the web worker cannot access the DOM. So we need to split a long task into small tasks and distribute them in the macrotask queue.

For example:

setTimeout(_ => {
  const start = performance.now()
  while (performance.now() - start < 1000) {}
  console.log('done!')
}, 5000)

The browser will get stuck for one second after the code is executed for five seconds.

We can use the chrome developer tool to capture the performance of the code run.

Now, we use time-slicing to cut long tasks, the code is as follows:

setTimeout(ts(function* () {
  const start = performance.now()
  while (performance.now() - start < 1000) {
    yield
  }
  console.log('done!')
}), 5000)

In the code, we use the yield keyword to split the code and distribute the code in different macrotask queues.

We can use the chrome developer tool to capture the performance of the code run.

From the figure we can see that the long task is gone, and replaced by a myriad of intensive small tasks.

time-slicing's People

Contributors

berwin avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.