From ff498190745fe5706e33dbd826abf921be22f89b Mon Sep 17 00:00:00 2001 From: Travis CI Date: Tue, 2 Jan 2018 08:38:48 +0000 Subject: [PATCH] Travis build: 835 [ci skip] --- README.md | 61 +++++++++++++++++++++++++++++++++++++++++++++++++ docs/index.html | 40 +++++++++++++++++++++++++++++++- 2 files changed, 100 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e0f09565..66b72362a 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,7 @@ * [`httpsRedirect`](#httpsredirect) * [`onUserInputChange`](#onuserinputchange) * [`redirect`](#redirect) +* [`runAsync`](#runasync) * [`scrollToTop`](#scrolltotop) * [`setStyle`](#setstyle) * [`show`](#show) @@ -1974,6 +1975,66 @@ redirect('https://google.com');
[⬆ Back to top](#table-of-contents) +### runAsync + +Runs a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI. + +Create a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function. +Immediately post the return value of calling the function back. +Return a promise, listening for `onmessage` and `onerror` events and resolving the data posted back from the worker, or throwing an error. + +```js +const runAsync = fn => { + const blob = ` + var fn = ${fn.toString()}; + this.postMessage(fn()); + `; + const worker = new Worker( + URL.createObjectURL(new Blob([blob]), { + type: 'application/javascript; charset=utf-8' + }) + ); + return new Promise((res, rej) => { + worker.onmessage = ({ data }) => { + res(data), worker.terminate(); + }; + worker.onerror = err => { + rej(err), worker.terminate(); + }; + }); +}; +``` + +
+Examples + +```js +const longRunningFunction = () => { + let result = 0; + for (var i = 0; i < 1000; i++) { + for (var j = 0; j < 700; j++) { + for (var k = 0; k < 300; k++) { + result = result + i + j + k; + } + } + } + return result; +}; + +// NOTE: Since the function is running in a different context, closures are not supported. +// The function supplied to `runAsync` gets stringified, so everything becomes literal. +// All variables and functions must be defined inside. +runAsync(longRunningFunction).then(console.log); // 209685000000 +runAsync(() => 10 ** 3).then(console.log); // 1000 +let outsideVariable = 50; +runAsync(() => typeof outsideVariable).then(console.log); // 'undefined' +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### scrollToTop Smooth-scrolls to the top of the page. diff --git a/docs/index.html b/docs/index.html index bf8aeebab..2bab29808 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
+    }

 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
 
Promise.resolve([1, 2, 3])
   .then(call('map', x => 2 * x))
   .then(console.log); //[ 2, 4, 6 ]
@@ -418,6 +418,44 @@ elementIsVisibleInViewport(el, true); // true // (partially visible)
 

redirect

Redirects to a specified URL.

Use window.location.href or window.location.replace() to redirect to url. Pass a second argument to simulate a link click (true - default) or an HTTP redirect (false).

const redirect = (url, asLink = true) =>
   asLink ? (window.location.href = url) : window.location.replace(url);
 
redirect('https://google.com');
+

runAsync

Runs a function in a separate thread by using a Web Worker, allowing long running functions to not block the UI.

Create a new Worker using a Blob object URL, the contents of which should be the stringified version of the supplied function. Immediately post the return value of calling the function back. Return a promise, listening for onmessage and onerror events and resolving the data posted back from the worker, or throwing an error.

const runAsync = fn => {
+  const blob = `
+    var fn = ${fn.toString()};
+    this.postMessage(fn());
+  `;
+  const worker = new Worker(
+    URL.createObjectURL(new Blob([blob]), {
+      type: 'application/javascript; charset=utf-8'
+    })
+  );
+  return new Promise((res, rej) => {
+    worker.onmessage = ({ data }) => {
+      res(data), worker.terminate();
+    };
+    worker.onerror = err => {
+      rej(err), worker.terminate();
+    };
+  });
+};
+
const longRunningFunction = () => {
+  let result = 0;
+  for (var i = 0; i < 1000; i++) {
+    for (var j = 0; j < 700; j++) {
+      for (var k = 0; k < 300; k++) {
+        result = result + i + j + k;
+      }
+    }
+  }
+  return result;
+};
+
+// NOTE: Since the function is running in a different context, closures are not supported.
+// The function supplied to `runAsync` gets stringified, so everything becomes literal.
+// All variables and functions must be defined inside.
+runAsync(longRunningFunction).then(console.log); // 209685000000
+runAsync(() => 10 ** 3).then(console.log); // 1000
+let outsideVariable = 50;
+runAsync(() => typeof outsideVariable).then(console.log); // 'undefined'
 

scrollToTop

Smooth-scrolls to the top of the page.

Get distance from top using document.documentElement.scrollTop or document.body.scrollTop. Scroll by a fraction of the distance from the top. Use window.requestAnimationFrame() to animate the scrolling.

const scrollToTop = () => {
   const c = document.documentElement.scrollTop || document.body.scrollTop;
   if (c > 0) {