Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!
A question about async and callbacks.

I get handing the async method a callback and that's not a problem. I can handle something like a Google Analytics API query a callback and the google library calls my function once the request is complete, great! But how does the google api actually manage the callback if its own process is asynchronous? At the point where the api sends off a method call to the internet, what process does it do to wait for the result and synchronously manage the callback?

Adbot
ADBOT LOVES YOU

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
JavaScript code:

var myCallback = function () {};

var asynchronousFunction = function (anotherCb) {
	setTimeout(anotherCb, 1000);
};

var anotherAsynchronousFunction = function (cb) {
	var myInnerCb = function () {
		cb();
	}

	asynchronousFunction(myInnerCb);
}

anotherAsynchronousFunction(myCallback);

Just Add More Functions!

qntm
Jun 17, 2009

Ahz posted:

A question about async and callbacks.

I get handing the async method a callback and that's not a problem. I can handle something like a Google Analytics API query a callback and the google library calls my function once the request is complete, great! But how does the google api actually manage the callback if its own process is asynchronous? At the point where the api sends off a method call to the internet, what process does it do to wait for the result and synchronously manage the callback?

I'm not 100% sure what you're asking. At the very bottom level you're probably going to find an XMLHttpRequest. Hugely simplified:

JavaScript code:
function googleApi(arg1, arg2, yourCallback) {

    // code (gets executed first)

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {

        // more code (gets executed third), such as:
        yourCallback();
    };
    xhr.open("GET", url);
    xhr.send();

    // more code (gets executed second)
}
Notice how the result from the XHR is handled by an anonymous inner function which has automatically captured yourCallback by reference. So when, some milliseconds later, that anonymous function is called, yourCallback is still in scope and can be called.

As for what happens inside XMLHttpRequest, itself, it's a JavaScript builtin, so a black box really.

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!

qntm posted:

I'm not 100% sure what you're asking. At the very bottom level you're probably going to find an XMLHttpRequest. Hugely simplified:

JavaScript code:
function googleApi(arg1, arg2, yourCallback) {

    // code (gets executed first)

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {

        // more code (gets executed third), such as:
        yourCallback();
    };
    xhr.open("GET", url);
    xhr.send();

    // more code (gets executed second)
}
Notice how the result from the XHR is handled by an anonymous inner function which has automatically captured yourCallback by reference. So when, some milliseconds later, that anonymous function is called, yourCallback is still in scope and can be called.

As for what happens inside XMLHttpRequest, itself, it's a JavaScript builtin, so a black box really.

Yeah I understand what you're saying. I guess I'm looking further down the rabbit hole into the black box.

DimpledChad
May 14, 2002
Rigging elections since '87.
The black box is pretty simple, at least the basic architecture. If you want to understand how the JS event loop works internally, this presentation is a great introduction:
https://www.youtube.com/watch?v=8aGhZQkoFbQ

Edit: This is the tool he's using in the video to visualize the event loop.

DimpledChad fucked around with this message at 21:13 on Apr 13, 2015

RICHUNCLEPENNYBAGS
Dec 21, 2010
How do you profile JavaScript (in-browser) for hotspots? I had some really slow-running code and I got it to acceptable with my spidey-sense but it would be nice to have some actual measurements to work with.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Use the Profiler in Chrome DevTools.

Load up the tab in DevTools, click Start, refresh your page and then hit stop when it's done loading..

Kekekela
Oct 28, 2004

DimpledChad posted:

The black box is pretty simple, at least the basic architecture. If you want to understand how the JS event loop works internally, this presentation is a great introduction:
https://www.youtube.com/watch?v=8aGhZQkoFbQ
Wow, very helpful. I didn't realize how much of that I didn't know. :downs:

Anony Mouse
Jan 30, 2005

A name means nothing on the battlefield. After a week, no one has a name.
Lipstick Apathy

Kekekela posted:

Wow, very helpful. I didn't realize how much of that I didn't know. :downs:
Ditto, good stuff.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

ArcticZombie posted:

Thanks, I solved the problem, but I can't understand why the first log has access to the object but the ones after it don't.

We'd have to see the rest of your code. I can virtually guarantee the answer will be somewhere else in your code than what you've included in your post.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'm working on a page which serves as a dashboard for a desktop app, and it keeps itself up to date with an ajax request for some json that's running on a timer.

The problem that I'm having is that the memory footprint of the browser is creeping up with every single call. It's slow, but this is the sort of page that might reasonably be expected to be open for hours at a time, and it'll be running on a mobile device.

It's a super simple refresh inside the loop,

JavaScript code:
$.ajax({
 url : '?Request=' + param,
 success : applyUpdatesToPage // edited per Wheany's observation
});
but it doesn't look like the downloaded data is getting garbage collected after the success callback has done its business (eg, updating a number or something). Any suggestions?

Newf fucked around with this message at 13:08 on Apr 17, 2015

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Newf posted:

I'm working on a page which serves as a dashboard for a desktop app, and it keeps itself up to date with an ajax request for some json that's running on a timer.

The problem that I'm having is that the memory footprint of the browser is creeping up with every single call. It's slow, but this is the sort of page that might reasonably be expected to be open for hours at a time, and it'll be running on a mobile device.

It's a super simple refresh inside the loop,

JavaScript code:
$.ajax({
 url : '?Request=' + param,
 success : applyUpdatesToPage(data)
});
but it doesn't look like the downloaded data is getting garbage collected after the success callback has done its business (eg, updating a number or something). Any suggestions?

In your example, you're calling applyUpdatesToPage immediately, is that what your actual code does? Because I don't think that would work, unless applyUpdatesToPage returns a function.

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.

Wheany posted:

In your example, you're calling applyUpdatesToPage immediately, is that what your actual code does? Because I don't think that would work, unless applyUpdatesToPage returns a function.

Sorry, yes, I do that every single time that I set a value to a function. The actual page sets the callback correctly and updates are applied.

silentpenguins
May 9, 2013

Abysswalking
Hey all,

Work is offering to pay for a conference to increase my awesomeness. Doing some basic googling I found JSConf and suggested that. If I'm mostly a backend guy who uses vanilla JS/JQuery when the need arises is this a good conference for me? I can pick things up pretty quickly and obviously a paid trip to JVille would be solid, but if I'm going to be out of my league for a lot of the conference I can find another one.

Thanks!

jkyuusai
Jun 26, 2008

homegrown man milk

silentpenguins posted:

Hey all,

Work is offering to pay for a conference to increase my awesomeness. Doing some basic googling I found JSConf and suggested that. If I'm mostly a backend guy who uses vanilla JS/JQuery when the need arises is this a good conference for me? I can pick things up pretty quickly and obviously a paid trip to JVille would be solid, but if I'm going to be out of my league for a lot of the conference I can find another one.

Thanks!

Do you mean JSConf US? According to their tickets page, it's sold out already. http://2015.jsconf.us/tickets.html

That conference is super duper popular and sells out really quick.

silentpenguins
May 9, 2013

Abysswalking

jkyuusai posted:

Do you mean JSConf US? According to their tickets page, it's sold out already. http://2015.jsconf.us/tickets.html

That conference is super duper popular and sells out really quick.

Cheaper tickets have sold out but the general admission Journey a few slots down is still for sale. Have you been?

jkyuusai
Jun 26, 2008

homegrown man milk

silentpenguins posted:

Cheaper tickets have sold out but the general admission Journey a few slots down is still for sale. Have you been?

Oh wow, totally missed that, my apologies. I haven't, but I've heard from some that have that they really enjoyed it. We've talked about doing it as a group some year since we're based in Tallahassee, but we always seem to forget come ticket time.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
So, I learned about Douglas Crockford's DEC64 and was thinking: Does Javascript actually require float (or double) specifically, or is it an implementation detail?

Could someone make a standards compliant Javascript interpreter that used for example DEC64?

Or does something in the standards say (or imply at least) that "0.1 + 0.2 == 0.3" must be false?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Wheany posted:

So, I learned about Douglas Crockford's DEC64 and was thinking: Does Javascript actually require float (or double) specifically, or is it an implementation detail?

Could someone make a standards compliant Javascript interpreter that used for example DEC64?

Or does something in the standards say (or imply at least) that "0.1 + 0.2 == 0.3" must be false?

The ECMAScript standard says that number type is "primitive value corresponding to a double-precision 64-bit binary format IEEE 754 value." A javascript implementation using DEC64 would violate the ECMAScript standard.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Welp, that's pretty conclusive.

Vulture Culture
Jul 14, 2003

I was never enjoying it. I only eat it for the nutrients.

Wheany posted:

Welp, that's pretty conclusive.
If you think that's bad, you should see the part in the standard where they explicitly tell implementers to calculate DST incorrectly instead of using the system's date/time facilities. (Thankfully, this one will be fixed in ES6.)

comedyblissoption
Mar 15, 2006

it's a lot better that javascript required a consistent number type across implementations instead of letting implementors choose the number type they felt like using

javascript only supporting one primitive number type is another matter

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

comedyblissoption posted:

it's a lot better that javascript required a consistent number type across implementations instead of letting implementors choose the number type they felt like using

javascript only supporting one primitive number type is another matter

Seriously. The only way to make the "only one number type" situation worse would be letting the implementor decide what it is.

ufarn
May 30, 2009
Anyone know whether it's possible to transpile the JS in an HTML file from es6 to es5?

Want to start using es6, but I prefer all the code in one file rather than editing the JS as an external file.

necrotic
Aug 2, 2005
I owe my brother big time for this!

ufarn posted:

Anyone know whether it's possible to transpile the JS in an HTML file from es6 to es5?

Want to start using es6, but I prefer all the code in one file rather than editing the JS as an external file.

You could maybe probably hack it in with something like:

code:
<script type="text/javascript-es6" id="transcode-me">
</script>
<script src="//whatever/transpiler.js"></script>
<script>
var code = document.getElementById('transcode-me').innerText;
eval(Transpiler.compile(code))
</script>
But that's pretty dumb. Just use a normal build process.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Most transpilers work based on the type attribute of the script tag. It should just work.

ufarn
May 30, 2009

Suspicious Dish posted:

Most transpilers work based on the type attribute of the script tag. It should just work.
Hmm, babel (FKA e6toe5) just reads the HTML file and throws an error at the first line ($ babel index.html). Haven't found anything by googling either. Guess I could install all the transpilers I can find and try manually, but it does sound like a pretty basic feature.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I've used Traceur with success in the past.

Subjunctive
Sep 12, 2006

✨sparkle and shine✨

ufarn posted:

Hmm, babel (FKA e6toe5) just reads the HTML file and throws an error at the first line ($ babel index.html). Haven't found anything by googling either. Guess I could install all the transpilers I can find and try manually, but it does sound like a pretty basic feature.

I think babel wants to work on out-of-line JS files, yeah. I can't blame them for not wanting to add HTML parsing to their workload.

The runtime transpilers will work from <script> tag type, but I don't know of any that will statically rewrite HTML. Have I forgotten that Traceur does that?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
I was assuming the poster meant runtime transpiling. I imagine it's not too difficult to hook up html5lib to some transpiler though if you still want a build step. I don't see the benefit of wanting a single file and also having a build step though.

ufarn
May 30, 2009

Subjunctive posted:

I think babel wants to work on out-of-line JS files, yeah. I can't blame them for not wanting to add HTML parsing to their workload.

The runtime transpilers will work from <script> tag type, but I don't know of any that will statically rewrite HTML. Have I forgotten that Traceur does that?
Traceur transpiles inline JS in production runtime, if you change <script>'s type attribute to "module" (and reference two external JS files), but I am looking for a CLI es6-html-to-es6-html compiler so I can just play around with es6 locally and use es5 in production. And for other reasons.

It seems weird that Traceur doesn't have a CLI open, when it can do it in runtime, but the docs don't seem to suggest a compile command not based on .js files.

ufarn fucked around with this message at 12:02 on Apr 22, 2015

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Suspicious Dish posted:

I was assuming the poster meant runtime transpiling. I imagine it's not too difficult to hook up html5lib to some transpiler though if you still want a build step. I don't see the benefit of wanting a single file and also having a build step though.

You'd get slightly better load times on ES < 6 browsers right? I mean, if you're that worried about it, it'd be better to just stick to ES5 but whatever.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
If you want a build step, use one of the HTML minifiers that will auto-include source for you if it thinks it's worth it.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

I like ES6 features too much. I've just resigned myself to having a build step for anything I do for a browser and have worked on making that as easy and transparent as possible for myself.

huhu
Feb 24, 2006
I'm an idiot.

huhu fucked around with this message at 01:24 on Apr 23, 2015

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

Thermopyle posted:

I like ES6 features too much. I've just resigned myself to having a build step for anything I do for a browser and have worked on making that as easy and transparent as possible for myself.

What's your toolchain like? What do you use for your builds?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

The Wizard of Poz posted:

What's your toolchain like? What do you use for your builds?

Depends on the project. I tend to have one ongoing project that lasts months with a few small things scattered here and there.

For simple needs, I have file watchers set up in my IDE (PyCharm/WebStorm) which automatically do my build stuff on each save.

The following is what I'm using on my current big project, and I'll reevaluate the state of the art when I get to my next project.

watchify -v --debug -t babelify js/main.js -o js/bundle.js

I try my best to only use libraries from npm since, despite its shortcomings, is far far better than bower or any of that other stupid poo poo. If a library I really need isn't on npm, I'll likely just download it and bundle it myself.

I also have npm set up to run the following when I run npm start.

mochify --watch --transform [babelify --ignore node_modules] --plugin [proxyquire-universal] --recursive

I've got that running in another terminal window.

And then I've got a stupid livereload server running with grunt running in another terminal window. I'm not really happy with it because of reasons I can't think of right now...

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
I'd like for a callback to be aware of whether or not this is the first time it has been called. My current solution works but I'd prefer to hide the firstRun toggle from the global scope.


JavaScript code:
var firstXrun = true;
function refreshX(){
  sendReq('X', callback);

  function callback(data){
    if (condition() && !firstXrun)
      // do stuff;
    }
    firstXrun = false; // we've now run
  }
}
Any suggestions for rearranging this?

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Newf posted:

I'd like for a callback to be aware of whether or not this is the first time it has been called. My current solution works but I'd prefer to hide the firstRun toggle from the global scope.


JavaScript code:
var firstXrun = true;
function refreshX(){
  sendReq('X', callback);

  function callback(data){
    if (condition() && !firstXrun)
      // do stuff;
    }
    firstXrun = false; // we've now run
  }
}
Any suggestions for rearranging this?

There's probably several ways. Here's one:

JavaScript code:
refreshX = (function (){
	var firstXrun = true;
	function refreshXInternal(){
	  sendReq('X', callback);

	  function callback(data){
	    if (condition() && !firstXrun) {
	      // do stuff;
	    }
	    firstXrun = false; // we've now run
	  }
	}
	return refreshXInternal;
})();
Edit: Maybe I should explain this better in case it isn't clear. (function (){ ... })(); is a pattern where you invoke an anomyous function immediately. Here I defined refreshXInternal in the anonymous function and returned it immediately, so refreshX is set to be that function. The difference is that now firstXrun is captured in the closure of the anonymous function and won't be visible to the outside world.

HappyHippo fucked around with this message at 18:27 on Apr 24, 2015

Adbot
ADBOT LOVES YOU

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Newf posted:

I'd like for a callback to be aware of whether or not this is the first time it has been called. My current solution works but I'd prefer to hide the firstRun toggle from the global scope.


JavaScript code:
var firstXrun = true;
function refreshX(){
  sendReq('X', callback);

  function callback(data){
    if (condition() && !firstXrun)
      // do stuff;
    }
    firstXrun = false; // we've now run
  }
}
Any suggestions for rearranging this?

Factory?

JavaScript code:
function getCallback() {
  var called = 0;
  return function (data) {
    //check the condition
    //do the thing
  }
}

//etc
sendReq('X', getCallback());
You could even make a generic callback wrapper if you want to re-use it.
JavaScript code:
//untested!
function limitCallsBackTo(someFunc, limit) {
  var total = 0;
  return function() {
    if (total++ < limit) {
      someFunc.apply(someFunc, arguments);
    }
  };
}

sendReq('X', limitCallsBackTo(handler, 1));
I imagine there's a library that's done the same thing only with testing, though ;)

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply