This talk was given at JSSummit 2013. Entitled "Avoiding Callback Hell with Async.js", my talk focused on common pitfalls with asynchronous functions and callbacks in JavaScript, and using the async.js library and its advanced control flows to create cleaner, more manageable code.
One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!
An introduction to promises from the ground up; an overview of the recent history of promises; and some guidance on using promises in your real-world code.
Video at http://www.youtube.com/watch?v=MNxnHbyzhuo, and article at http://open.blogs.nytimes.com/2013/05/29/promises-promises/.
A few slides about asynchrnous programming in Node, from callback hell to control flows using promises, thunks and generators, providing the right amount of abstraction to write great code.
All examples available on https://github.com/troch/node-control-flow.
This talk was given at JSSummit 2013. Entitled "Avoiding Callback Hell with Async.js", my talk focused on common pitfalls with asynchronous functions and callbacks in JavaScript, and using the async.js library and its advanced control flows to create cleaner, more manageable code.
One of JavaScript’s strengths is how it handles asynchronous code. Async is one of the most important and often misunderstood part of Javascript or any other language. Async is hard because we, as human beings, can’t do two conscious actions at once and think about both of them at the same moment. In this talk we will see how asynchronous JavaScript evolved over the years. It all started with callbacks… and it landed on generators!
An introduction to promises from the ground up; an overview of the recent history of promises; and some guidance on using promises in your real-world code.
Video at http://www.youtube.com/watch?v=MNxnHbyzhuo, and article at http://open.blogs.nytimes.com/2013/05/29/promises-promises/.
A few slides about asynchrnous programming in Node, from callback hell to control flows using promises, thunks and generators, providing the right amount of abstraction to write great code.
All examples available on https://github.com/troch/node-control-flow.
Presentation I gave to the node.dc meetup group March 13, 2013 on using Promises and the Q library to make flow of control easier to reason about in Javascript code using async and callbacks
Promises are a popular pattern for asynchronous operations in JavaScript, existing in some form in every client-side framework in widespread use today. We'll give a conceptual and practical intro to promises in general, before moving on to talking about how they fit into Angular. If you've ever wondered what exactly $q was about, this is the place to learn!
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
A presentation of what are JavaScript Promises, what problems they solve and how to use them. Dissects some Bluebird features, the most complete Promise library available for NodeJS and browser.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
A short introduction to the concepts of functional reactive programming, and their implementation in ReactiveCocoa, a framework for iOS and OS X developers.
This speech was given at CocoaHeads Paris, October 9th 2014
Slowly but surely, promises have spread throughout the JavaScript ecosystem, standardized by ES 2015 and embraced by the web platform. But the world of asynchronous programming contains more patterns than the simple single-valued async function call that promises represent. What about things like streams, observables, async iterators—or even just cancelable promises? How do they fit, both in the conceptual landscape and in your day-to-day programming?
For the last year, I've been working to bring an implementation of I/O streams to the browser. Meanwhile, designs for a cancelable promise type (sometimes called "tasks") are starting to form, driven by the needs of web platform APIs. And TC39 has several proposals floating around for more general asynchronous iteration. We'll learn about these efforts and more, as I guide you through the frontiers of popular libraries, language design, and web standards.
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
Presentation I gave to the node.dc meetup group March 13, 2013 on using Promises and the Q library to make flow of control easier to reason about in Javascript code using async and callbacks
Promises are a popular pattern for asynchronous operations in JavaScript, existing in some form in every client-side framework in widespread use today. We'll give a conceptual and practical intro to promises in general, before moving on to talking about how they fit into Angular. If you've ever wondered what exactly $q was about, this is the place to learn!
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
A presentation of what are JavaScript Promises, what problems they solve and how to use them. Dissects some Bluebird features, the most complete Promise library available for NodeJS and browser.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
(Presented at JSConf US 2013. Be sure to check out the speaker notes!)
Frustration, a rant, a test suite, a gist. Then, community awesomeness. Boom! Promises/A+ was born.
Promise are an old idea for abstracting asynchronous code, but have only recently made their way into JavaScript. We'll look at the power they provide via two striking examples that go beyond the usual "escape from callback hell" snippets. First we'll show how, with ES6 generators, they can act as shallow coroutines to give us back code just as simple as its synchronous counterpart. Then we'll look at how they can be used as proxies for remote objects, across <iframe>, worker, or web socket boundaries.
However, the most interesting aspect of Promises/A+ is not just the code it enables, but how we worked to create it. We didn't join a standards body, but instead formed a GitHub organization. We had no mailing list, only an issue tracker. We submitted pull requests, made revisions, debated versions tags, etc.—all in the open, on GitHub. And, we succeeded! Promises/A+ is widely used and implemented today, with its extensible core forming the starting point of any discussions about promises. Indeed, this community-produced open standard has recently been informing the incorporation of promises into ECMAScript and the DOM. I'd like to share the story of how this happened, the lessons we learned along the way, and speculate on the role such ad-hoc, community-driven, and completely open specifications have for the future of the web.
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
A short introduction to the concepts of functional reactive programming, and their implementation in ReactiveCocoa, a framework for iOS and OS X developers.
This speech was given at CocoaHeads Paris, October 9th 2014
Slowly but surely, promises have spread throughout the JavaScript ecosystem, standardized by ES 2015 and embraced by the web platform. But the world of asynchronous programming contains more patterns than the simple single-valued async function call that promises represent. What about things like streams, observables, async iterators—or even just cancelable promises? How do they fit, both in the conceptual landscape and in your day-to-day programming?
For the last year, I've been working to bring an implementation of I/O streams to the browser. Meanwhile, designs for a cancelable promise type (sometimes called "tasks") are starting to form, driven by the needs of web platform APIs. And TC39 has several proposals floating around for more general asynchronous iteration. We'll learn about these efforts and more, as I guide you through the frontiers of popular libraries, language design, and web standards.
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
Dive into core asynchronous patterns in modern JavaScript. Comparing the tradeoffs of callbacks, thunks, promises, generators and async/await and demonstrating how each pattern builds on top of the previous. Touching on concepts like the Event Queue, Single-threaded, Run to Completion and Non-Blocking. Showing how we can deal with things happening “at the same time“ and maybe even completely eliminate time as a concern.
Promises are so passé - Tim Perry - Codemotion Milan 2016Codemotion
Promises saved JavaScript from callback hell, but we’re not out of the woods yet. Anybody who’s written heavily asynchronous code knows there’s still pain in the promise’d land, from the flood of extra ceremony required to the frustratingly fractured function scope. Fortunately, this isn’t the end of the line, and with generators and JavaScript's upcoming async/await syntax we can do even better. In this talk we’ll look at where asynchronous development is going next, how it’s going solve your problems, and what you need to do to put it into practice today.
IS YOUR WIDGET FAST? FIVE BEST PRACTICES TO FASTER EMBEDDABLE CONTENTIsmail Elshareef
Widgets have a bad rap but they are also a fact of life. Starting from the most ubiquitous (e.g. ads) to the niche, widgets are everywhere. These slides present five best practices that lead to fast, unobtrusive embeddable code that is a welcome addition on any page.
JavaScript basics
JavaScript event loop
Ajax and promises
DOM interaction
JavaScript object orientation
Web Workers
Useful Microframeworks
This presentation has been developed in the context of the Mobile Applications Development course, DISIM, University of L'Aquila (Italy), Spring 2014.
http://www.ivanomalavolta.com
A design pattern provides a general reusable solution for the common problems that occur in software design. The pattern typically shows relationships and interactions between classes or objects. The idea is to speed up the development process by providing well-tested, proven development/design paradigms. Design patterns come in three different categories. Creational patterns include the generation of object instances. Structure refers to how an object is made and how things behave and interact In this Webinar(Live Meetup) we will be covering - What is node js - When to use node js - Async I/O operations in node js - Advantages of Async/Await - Some interesting - async patterns - Performance comparison
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
Salah satu front-end developer GITS Indonesia, Warsono, mengisi workshop di universitas, mengenai Vue.js.
Ikuti kami di kanal berikut, agar tidak ketinggalan acara seru:
Instagram: @gitsindonesia
LinkedIn: GITS Indonesia
Website: gits.id
A presentation about the Service Worker.
Talk about the difference between AppCache and ServiceWorker, also show as possible with him and the idea for the future.
Demo: https://github.com/brunoosilva/service-worker
As a guest speaker in NCU, I gave this second talk about some more advanced practices of JavaScript programming. It summarised our experience learned from developing Mozilla/Gaia project, including the way to deal with asynchronous code flow with the event-driven model.
Why do we need promises? How does promises compare to a simple callback approach or modules like async? Are promises just a hype or a new standard for asynchronous code?
Describes the overview process and technique of lazy loading javascript from external 3rd parties or your own in-house stuff and provides a simple example with the possible benefits for large javascript applications.
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
JavaScript is single threaded, so understanding the async patterns available in the language is critical to creating maintainable NodeJS applications with good performance. In order to master “thinking in async”, we’ll explore the async patterns available in node and JavaScript including standard callbacks, promises, thunks/tasks, the new async/await, the upcoming asynchronous iteration features, streams, CSP and ES Observables.
Presented 9/12/2009 at jQuery Conf 2009.
Like any good Javascript framework would, jQuery includes Ajax functionality into its core. In particular, though, jQuery has some interesting ways it approaches event handling with Ajax responses. We’re going to dive into this Ajax event mechanism, and see what fun we can have with extending it.
This talk will first review the various Ajax events and some common ways they are used. Then, we’ll investigate jQuery source code and see how each is accomplished. Armed with this knowledge, we’ll talk about some scenarios where you might want to extend these events with extra functionality, or even add your own custom Ajax events.
To move from the theoretical into the concrete, we will discuss two jQuery Ajax plugins I released, mpAjax and flXHRproxy, and look at how each needed in its own way to hook into the Ajax event mechanism and extend it.
Similar to Understanding Asynchronous JavaScript (20)
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBrad Spiegel Macon GA
Brad Spiegel Macon GA’s journey exemplifies the profound impact that one individual can have on their community. Through his unwavering dedication to digital inclusion, he’s not only bridging the gap in Macon but also setting an example for others to follow.
This 7-second Brain Wave Ritual Attracts Money To You.!nirahealhty
Discover the power of a simple 7-second brain wave ritual that can attract wealth and abundance into your life. By tapping into specific brain frequencies, this technique helps you manifest financial success effortlessly. Ready to transform your financial future? Try this powerful ritual and start attracting money today!
Multi-cluster Kubernetes Networking- Patterns, Projects and GuidelinesSanjeev Rampal
Talk presented at Kubernetes Community Day, New York, May 2024.
Technical summary of Multi-Cluster Kubernetes Networking architectures with focus on 4 key topics.
1) Key patterns for Multi-cluster architectures
2) Architectural comparison of several OSS/ CNCF projects to address these patterns
3) Evolution trends for the APIs of these projects
4) Some design recommendations & guidelines for adopting/ deploying these solutions.
1.Wireless Communication System_Wireless communication is a broad term that i...JeyaPerumal1
Wireless communication involves the transmission of information over a distance without the help of wires, cables or any other forms of electrical conductors.
Wireless communication is a broad term that incorporates all procedures and forms of connecting and communicating between two or more devices using a wireless signal through wireless communication technologies and devices.
Features of Wireless Communication
The evolution of wireless technology has brought many advancements with its effective features.
The transmitted distance can be anywhere between a few meters (for example, a television's remote control) and thousands of kilometers (for example, radio communication).
Wireless communication can be used for cellular telephony, wireless access to the internet, wireless home networking, and so on.
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC
Ellisha Heppner, Grant Management Lead, presented an update on APNIC Foundation to the PNG DNS Forum held from 6 to 10 May, 2024 in Port Moresby, Papua New Guinea.
3. “There are two hard things in
computer science: cache
invalidation, naming things,
and off-by-one errors.
- Unknown
Somebody go to Google and search "define synchronous"
4. Wikipedia
codewala.net
Our Simple Definition
Parallel computing is a form of computation in which many calculations are carried
out simultaneously, operating on the principle that large problems can often be
divided into smaller ones, which are then solved concurrently ("in parallel").
Asynchronous operation means that a process operates independently of other
processes. If there are multiple operations, [they] can be handled [using] different
processes/threads without waiting to complete the other ones.
When the flow of your program is such that code might be executed out
of order or you might not be able to count on one thing happening
before another thing.
6. // Define some functions
JS
function first() {
return 'hello';
}
function second() {
return first();
}
function third() {
first();
return second();
}
function fourth() {
first();
second();
return third();
}
// Execute the program
01 first();
02 second();
03 third();
04 fourth();
Code is executed in a "single thread."
7. // Define some functions
JS
01 function last() {
02 console.log("from L.A. to Tokyo");
03 }
04 function doProgram() {
05 setTimeout(last, 0);
06 console.log("i'm so fancy");
07 console.log("you already know");
08 console.log("i'm in the fast lane");
09 }
// Execute the program
10 doProgram();
!
//=> i'm so fancy
//=> you already know
//=> i'm in the fast lane
//=> from L.A. to Tokyo
8. “
When there is nothing to do,
Check the queue.
But only check the queue
When there's nothing left to do.
- JavaScript
In other words, the current flow will NEVER be
interrupted by code existing in the queue.
9. // Add a click handler to the document.
document.addEventListener('click', function () {
console.log('click happened!');
});
!
// Create a function that does nothing but waste time.
function wasteTime() {
var i;
for (i = 0; i < 3000000; i += 1) {
new Array(10000000);
}
return 'finished wasting time';
}
!
// Start wasting time.
wasteTime();
JS
//=> finished wasting time
//=> click happened!
Let's prove it in the console!
10. JS
Some similar examples that
use the queue:
[ELEMENT].addEventListener('click', myFunction);
!
[ELEMENT].onclick = myFunction;
!
$([ELEMENT]).click(myFunction);
!
<a onclick="myFunction">click me</a>
The queue matters because any time your program
receives input, JavaScript puts the input handler
into the queue.
11. So when we talk about
"asynchronous JavaScript,"
we're really just talking
about any code that puts
things in the queue.
12. And if we can't know when code
will enter the queue (for example,
application input), we can't
know when it will be executed.
13. 1 2 3
Ways to Receive Input
DOM events such as
clicks, hovers, keyups,
etc.
!
!
Handlers go in the
queue.
HTTP(s)/websocket
communication events.
(Includes $.ajax)
!
!
Handlers go in the
queue.
Web worker message
passing. (How we do
threads in the browser)
!
!
Handlers go in the
queue.
14. And if it's in the queue,
you can't return it or
error handle it.
15. function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax;
}
!
getGithubInfo();
JSLet's access some real data:
16. function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax;
}
!
getGithubInfo();
JSLet's access some real data:
NOPE!
But clearly that's because $.ajax is returning the jQuery
request object instead of the actual data. Let's fix that.
17. function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax.done(function (data) {
return data;
});
}
!
getGithubInfo();
JSLet's access some real data:
18. function getGithubInfo() {
var ajax = $.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
});
return ajax.done(function (data) {
return data;
});
}
!
getGithubInfo();
JSLet's access some real data:
STILL NOPE!
Right, but this time it's because .done is a Promise method so it's
returning another Promise object. I got it this time…
19. function getGithubInfo() {
var result;
$.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
}).done(function (data) {
result = data;
});
return result;
}
!
getGithubInfo();
JSLet's access some real data:
20. function getGithubInfo() {
var result;
$.ajax({
url: 'https://api.github.com/users/jgnewman/repos',
dataType: 'jsonp'
}).done(function (data) {
result = data;
});
return result;
}
!
getGithubInfo();
JSLet's access some real data:
FRACK! STILL NOPE!
Because no matter what we do, ajax requires an event handler and
event handlers go into the queue. Which means…
29. // Import the file system library
var fileSystem = require('fs');
!
// Call `readdir` (which is asynchronous) to get a list
// of files in the directory
fileSystem.readdir('/myfiles', function (err, data) {
if (err) {
handleTheError(err);
} else {
doSomethingWith(data);
}
});
JSWhat Everyone Hates About
Node.js
What's wrong with this pattern, you ask?
30. /**
* Show a list of songs for the artist with the given name and
* execute the callback when complete.
*/
function showSongs(artistName, callback) {
// Notice we're not even thinking about errors here
artists.getByName(artistName, function (artist) {
albums.getByArtist(artist, function (albums) {
songs.getByAlbum(albums, function (songs) {
songView.render(songs);
return callback();
});
});
});
}
JSThe fact that it gets nasty
really fast:
example stolen from clutchski on slideshare
31. Can Promises fix that
problem?
The can definitely ice that cake.
32. What is a Promise?
‣ It's an object with methods (usually done, then, and fail).
‣ Each method takes at least 1 callback.
‣ The callbacks are executed under different conditions
(done or then on success, fail on error ).
‣ Each Promise method returns another promise.
‣ Therefore, you can chain asynchronous actions.
‣ And you can attach as many callbacks as you want to a
given event.
34. So let's go back to our
ugly, nested callbacks.
35. /**
* Show a list of songs for the artist with the given name and
* execute the callback when complete.
*/
function showSongs(artistName, callback) {
artists.getByName(artistName, function (artist) {
albums.getByArtist(artist, function (albums) {
songs.getByAlbum(albums, function (songs) {
songView.render(songs);
return callback();
});
});
});
}
JSPreviously we had this:
36. /**
* Show a list of songs for the artist with the given name and
* execute the callback when complete.
*/
function showSongs(artistName, callback) {
artists.getByName(artistName)
.then(function (artist) { return albums.getByArtist(artist) })
.then(function (albums) { return songs.getByAlbum(albums) })
.then(function (songs) { return songView.render(songs) })
.then(callback);
}
JSBut if we used promises
instead…
Promises are going to be native in ES6! (Currently 0 IE support)
37. jQuery
Tons of Others
Q for Node.js
http://api.jquery.com/promise/
http://promisesaplus.com/implementations
https://github.com/kriskowal/q
38. At this point, you may be
wondering…
‣ Why asynchrony is always talked about in terms of
concurrency when the word itself seems to imply the
exact opposite
‣ What asynchronous JavaScript looks like using web
workers
‣ When this talk is going to end
(Check the time, future John)
40. Evaluate main
thread and worker
thread
JS
Queue
Queue
Main thread sends
message to worker
which goes into
the worker's
queue
Worker sends
message to main
thread which goes
into main
thread's queue
Each thread can be
run on its own core
thus making multiple
actions actually
simultaneous.
Every time a message
is sent, that message
goes into a queue
thus making the code
within each thread
independently
asynchronous.
41. A web worker is…
‣ A way to spin up multiple threads in browser-based
JavaScript
‣ Theoretically, an extremely helpful tool that has been
much needed for quite some time
‣ In reality, a fairly annoying and cumbersome
implementation of a concept that ought to have been
much simpler
42. JS
var worker = new Worker('myworker.js');
!
worker.onmessage = function (evt) {
console.log('The worker sent', evt.data);
};
!
worker.postMessage('');
JS
self.onmessage = function () {
self.postMessage('message received');
};
main.js myworker.js
43. // Takes a function and turns it into a web worker
function createWorker(fn) {
var body = fn.toString().replace(/^.+{|}s*$/g, ''),
blob = new Blob([body], {type: 'text/javascript'});
return new Worker(window.URL.createObjectURL(blob));
}
JS
There's also a "secret" way to do it
with one file:
// The intended functionality of our web worker
function workerBody() {
self.onmessage = function () {
self.postMessage('message received');
};
}
// Create and use the worker
var worker = createWorker(workerBody);
worker.onmessage = function (evt) {
console.log('The worker sent', evt.data);
};
worker.postMessage('');
44. JS
Let's use it to make life a bit easier:
// The minified worker maker
function createWorker(f){var b=f.toString().replace(/^.+{|}s*$/g,''),l=new
Blob([b],{type:'text/javascript'});return new Worker(window.URL.createObjectURL(l))}
!
// A worker body containing a modified version of our time wasting function from before.
// Creates 3 million arrays with 10 million items and returns the amount of
// time that took.
function workerBody() {
function wasteTime() {
var i, begin = Date.now();
for (i = 0; i < 3000000; i += 1) {
new Array(10000000);
}
return Date.now() - begin;
}
self.onmessage = function () {
var time = wasteTime();
self.postMessage('Wasted ' + time + 'ms of time.');
};
}
!
// Set up a click handler on the document
var clicks = 0;
document.addEventListener('click', function () { console.log('click', ++clicks, 'happened') });
!
// Launch the worker and try it out.
var worker = createWorker(workerBody);
worker.onmessage = function (evt) { console.log(evt.data) };
worker.postMessage();
46. STREAMPUNK
!
A simple & surprisingly powerful
application framework that offers data
binding, single page apps, and tons of
other tools.
!
streampunkjs.com
SOLID FUEL
SOCKET BOOSTER
!
A library for the browser that allows you
to take common ajax/websocket actions
and dynamically run them within a web
worker.
!
github.com/jgnewman/sfsb
47. You can also check out
htmlgoodies.com for
more examples of Web
Workers in action.
http://www.htmlgoodies.com/html5/client/introduction-
to-html5-web-workers-use-cases-and-identify-hot-
spots-.html