Socket
Socket
Sign inDemoInstall

zone.js

Package Overview
Dependencies
Maintainers
1
Versions
124
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

zone.js

Zones for JavaScript


Version published
Weekly downloads
3.1M
decreased by-10.61%
Maintainers
1
Weekly downloads
 
Created

Package description

What is zone.js?

The zone.js package is a library that implements Zones for JavaScript. Zones are execution contexts that allow you to intercept and keep track of asynchronous operations in JavaScript. This is particularly useful for debugging, performance tracking, and managing multiple tasks in complex applications such as Angular.

What are zone.js's main functionalities?

Error Handling

Intercepts errors within a specific zone and allows custom error handling.

Zone.current.fork({
  name: 'errorHandlingZone',
  onHandleError: (parentZoneDelegate, currentZone, targetZone, error) => {
    console.error('Error intercepted in zone:', error);
    return false;
  }
}).run(() => {
  throw new Error('Test Error');
});

Execution Context Tracking

Tracks the scheduling and execution of asynchronous tasks, providing insights into the application's asynchronous flow.

Zone.current.fork({
  name: 'trackingZone',
  onScheduleTask: (delegate, currentZone, targetZone, task) => {
    console.log('Task scheduled:', task.source);
    return delegate.scheduleTask(targetZone, task);
  }
}).run(() => {
  setTimeout(() => {
    console.log('Timeout callback executed.');
  }, 1000);
});

Performance Monitoring

Measures the time taken to execute asynchronous tasks, which can be used for performance analysis.

Zone.current.fork({
  name: 'performanceMonitoringZone',
  onInvokeTask: (delegate, currentZone, targetZone, task, applyThis, applyArgs) => {
    const start = performance.now();
    delegate.invokeTask(targetZone, task, applyThis, applyArgs);
    const duration = performance.now() - start;
    console.log('Task took:', duration, 'ms');
  }
}).run(() => {
  setTimeout(() => {
    console.log('Timeout callback executed.');
  }, 1000);
});

Other packages similar to zone.js

Readme

Source

Zone.js

Build Status

Implements Zones for JavaScript.

What's a Zone?

A Zone is an execution context that persists across async tasks. You can think of it as thread-local storage for JavaScript VMs.

See this video from ng-conf 2014 for a detailed explanation:

screenshot of the zone.js presentation and ng-conf 2014

Running Within a Zone

You can run code within a zone with zone.run. Tasks scheduled (with setTimeout, setInterval, or event listeners) stay within that zone.

zone.run(function () {
  zone.inTheZone = true;

  setTimeout(function () {
    console.log('in the zone: ' + !!zone.inTheZone);
  }, 0);
});

console.log('in the zone: ' + !!zone.inTheZone);

The above will log:

'in the zone: false'
'in the zone: true'

Note that the function delayed by setTimeout stays inside the zone.

Forking a Zone

Zones have a set of hooks that allow you to change the behavior of code running within that zone. To change a zone, you fork it to get a new one.

zone.fork({
  onZoneEnter: function () {
    console.log('hi');
  }
}).run(function () {
  // do stuff
});

Hooks that you don't override when forking a zone are inherited from the existing one.

See the API docs below for more.

Examples

There are two kinds of examples:

  1. The kind you have to run
  2. Illustrative code snippets in this README

Running the ones that you have to run

For fully working examples:

  1. Spawn a webserver in the root of the directory in which this repo lives. (I like to use python -m SimpleHTTPServer 3000).
  2. Open http://localhost:3000/example in your browser

Below are the aforementioned snippets.

Tracking VM Turns

Run some function at the end of each VM turn:

zone.fork({
  onZoneLeave: function () {
    // do some cleanup
  }
}).run(function () {
  // do stuff
});

Overriding A Zone's Hook

var someZone = zone.fork({
  onZoneLeave: function () {
    console.log('goodbye');
  }
});

someZone.fork({
  onZoneLeave: function () {
    console.log('cya l8r');
  }
}).run(function () {
  // do stuff
});

// logs: cya l8r

Augmenting A Zone's Hook

When you fork a zone, you'll often want to control how the parent zone's hook gets called.

Prefixing a hook with $ means that the hook will be passed the parent zone's hook, and the hook will be expected to return the function to be invoked rather than be the function itself.

var someZone = zone.fork({
  onZoneLeave: function () {
    console.log('goodbye');
  }
});

someZone.fork({
  $onZoneLeave: function (parentOnLeave) {
    // return the hook
    return function onZoneLeave() {
      parentOnLeave();
      console.log('cya l8r');
    };
  }
}).run(function () {
  // do stuff
});

// logs: goodbye
//       cya l8r
+ and - Sugar

Most of the time, you'll want to run a hook before or after the parent's implementation. You can prefix a hook with - for running before, and + for running after.

The above can be written like this:

var someZone = zone.fork({
  onZoneLeave: function () {
    console.log('goodbye');
  }
});

someZone.fork({
  '+onZoneLeave': function (parentOnLeave) {
    console.log('cya l8r');
  }
}).run(function () {
  // do stuff
});

// logs: goodbye
//       cya l8r

This frees you from writing boilerplate to compose a new hook.

API

Zone.js exports a single object: window.zone.

zone.run

Runs a given function within the zone. Explained above.

zone.bind

Transforms a function to run within the given zone.

zone.fork

zone.fork({
  onZoneEnter: function () {},
  onZoneLeave: function () {},
  onError: function () {},
  setTimeout: function () {},
  setInterval: function () {},
  alert: function () {},
  prompt: function () {},
  addEventListener: function () {}
});
myZone.run(function () {
  // woo!
});

Below describes the behavior of each of these hooks.

zone.onZoneCreated

Runs when a zone is forked.

zone.onZoneEnter

Before a function invoked with zone.run, this hook runs. If zone.onZoneEnter throws, the function passed to run will not be invoked.

zone.onZoneLeave

After a function in a zone runs, the onZoneLeave hook runs. This hook will run even if the function passed to run throws.

zone.onError

This hook is called when the function passed to run or the onZoneEnter hook throws.

zone.setTimeout, zone.setInterval, zone.alert, zone.prompt

These hooks allow you to change the behavior of window.setTimeout, window.setInterval, etc. While in this zone, calls to window.setTimeout will redirect to zone.setTimeout.

zone.addEventListener

This hook allows you to intercept calls to EventTarget.addEventListener.

Status

  • setTimeout, setInterval, and addEventListener work in FF23, IE10, and Chrome.
  • stack trace rewrite is kinda ugly and may contain extraneous calls.
  • elt.onevent works in FF23, IE10, but not Chrome. There's a fix in the works though!

See also

License

Apache 2.0

FAQs

Package last updated on 31 Mar 2014

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc