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
Roadie
Jun 30, 2013

geeves posted:

Immutable.js and Collections.js are both really good. But I've been leaning towards Immutable. It helps that they both mirror Collections in Java

For me, the key thing about Immutable.js is that Seq is lazily processed but is directly compatible with everything else in the library. Really helps with gigantic data sets and the like.

Adbot
ADBOT LOVES YOU

Dominoes
Sep 20, 2007

Hi. I'm looking for advice on connecting React to Redux, using a trivial example. This page is an official guide, but I'm having trouble following it.

Here's a working setup using just React, and example data passed in at the bottom:
JavaScript code:
class WarningComp extends React.Component<any, any> {
    render() {
        return (
            <h5>{this.props.warning.description}</h5>
        )
    }
}



class Warnings extends React.Component<any, any> {
    renderWarnings() {
        return this.props.warnings.map(warning => <WarningComp warning={warning} />)
    }

    render() {
        return (
            <div>
                {this.renderWarnings()}
            </div>
        )
    }
}

export function run2() {
    let warnings = [{description: "TEST 1"}, {description: "TEST 2"}]  // These show up.

    ReactDOM.render(
            <Warnings warnings={warnings} />,
         document.getElementById('warnings'))
}
I'm using these bits of code to hook up my state, but can't get it to work. The data is stored as an array, retrievable with 'state.store.getState().warnings'. The state is fully-functional, when used with getState(), and dispatch. I don't really understand this code; I'm just trying to follow the official example.

JavaScript code:

const mapStateToProps = (state) => {
    return {
        warnings: state.warnings
    }
}


const mapDispatchToProps = (dispatch) => {
    return {

    }
}


const ConnectedWarnings = connect(
    mapStateToProps,
    mapDispatchToProps
)(Warnings)

export function run() {
        return
    ReactDOM.render(
        <Provider store={state.store}>
            <ConnectedWarnings />
        </Provider>, document.getElementById('warnings'))
}

Dominoes fucked around with this message at 18:29 on Apr 28, 2017

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dominoes posted:

Hi. I'm looking for advice on connecting React to Redux, using a trivial example. This page is an official guide, but I'm having trouble following it.



A quick look doesn't show anything "off", except the state.store thing. Is that the right name? What happens if you log this.props.warnings inside your renderWarnings function? You checked that the empty object for mapDispatchToProps isn't causing problems? (You also don't need to put it in there if you don't have any actions) Also, your run and run2 functions differ in that one returns the result of render, the other does not (shouldn't matter, but it's a difference)

You also don't need to use class-based components if you aren't going to use any lifecycle / internal state so you can simplify your code a bunch. See if something this works (check for typos first =):

JavaScript code:
const WarningComp = ({ warning }) => <h5>{ warning.description }</h5>

const Warnings = ({ warnings }) => (
<div>
  { warnings.map( w => <WarningComp warning={ w } /> ) }
</div>
)

const mapStateToProps = (state) => {
        warnings: state.warnings
}
// you could get fancy with
// const mapStateToProps = ({ warnings }) => { warnings }


const ConnectedWarnings = connect(mapStateToProps)(Warnings);

Lumpy fucked around with this message at 19:38 on Apr 28, 2017

Dominoes
Sep 20, 2007

Thanks dude! Going to have a look in a bit.

geeves
Sep 16, 2004

Dominoes posted:

Hi. I'm looking for advice on connecting React to Redux, using a trivial example. This page is an official guide, but I'm having trouble following it.

Here's a working setup using just React, and example data passed in at the bottom:


I wish the Redux tutorials would focus more on Redux and not gimmick "cleaner" hipster sperg ways of ES6. Plus when I hear his voice I just want to scream "stop talking!"

Dominoes
Sep 20, 2007

Lumpy posted:

A quick look doesn't show anything "off", except the state.store thing. Is that the right name? What happens if you log this.props.warnings inside your renderWarnings function? You checked that the empty object for mapDispatchToProps isn't causing problems? (You also don't need to put it in there if you don't have any actions) Also, your run and run2 functions differ in that one returns the result of render, the other does not (shouldn't matter, but it's a difference)

You also don't need to use class-based components if you aren't going to use any lifecycle / internal state so you can simplify your code a bunch. See if something this works (check for typos first =):

JavaScript code:
const WarningComp = ({ warning }) => <h5>{ warning.description }</h5>

const Warnings = ({ warnings }) => (
<div>
  { warnings.map( w => <WarningComp warning={ w } /> ) }
</div>
)

const mapStateToProps = (state) => {
        warnings: state.warnings
}
// you could get fancy with
// const mapStateToProps = ({ warnings }) => { warnings }


const ConnectedWarnings = connect(mapStateToProps)(Warnings);

I got your functional/no-boilerplate approach working with the non-redux run func. Much easier to read - thanks for the learning!

When I use the connected version, this.props.warnings now just warnings, re above, is undefined. For context, 'state' in 'state.store' is just the module I keep the state in. Removing mapToDispatch from connect() doesn't fix it. I have a feeling this is just me missing some critical bit of syntax.

geeves, I thought the first few videos/intro pages describing the basic redux flow/mindset were decent, although they could have used simpler examples to demonstrate the syntax. The ES6 syntax is nicer, so why not use it? JS without it is quite unpleasant! Ie picture that .map statement with i++ syntax. I'm still holding out on abolishing braces... not a chance?

Dominoes fucked around with this message at 00:47 on Apr 29, 2017

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dominoes posted:

I got your functional/no-boilerplate approach working with the non-redux run func. Much easier to read - thanks for the learning!

When I use the connected version, this.props.warnings now just warnings, re above, is undefined. For context, 'state' in 'state.store' is just the module I keep the state in. Removing mapToDispatch from connect() doesn't fix it. I have a feeling this is just me missing some critical bit of syntax.

geeves, I thought the first few videos/intro pages describing the basic redux flow/mindset were decent, although they could have used simpler examples to demonstrate the syntax. The ES6 syntax is nicer, so why not use it? JS without it is quite unpleasant! Ie picture that .map statement with i++ syntax. I'm still holding out on abolishing braces... not a chance?

I wonder if it's a name collision with the 'state' thing you keep your store in. Out of curiosity, why? Your store should be its Own Thing.

Met48
Mar 15, 2009
You also need parentheses around the object you're returning, ie.

code:
const mapStateToProps = (state) => ({
        warnings: state.warnings
})

geeves
Sep 16, 2004

Dominoes posted:

geeves, I thought the first few videos/intro pages describing the basic redux flow/mindset were decent, although they could have used simpler examples to demonstrate the syntax. The ES6 syntax is nicer, so why not use it? JS without it is quite unpleasant! Ie picture that .map statement with i++ syntax. I'm still holding out on abolishing braces... not a chance?

They absolutely are! I just knew very little about ES6 and what all the changes were outside of let and const and class. So having new language concepts and shortcuts thrown in took me out of an "Intro" to a new framework when I had to remind myself what "..." did and missed the actual important piece that array.foo() actually mutates the array while .bar() does not.

If anything it was good because I didn't really need redux and decided instead to get used to everything new in ES6 first. Now I won't have this problem when I return to redux.

Dominoes
Sep 20, 2007

Lumpy posted:

I wonder if it's a name collision with the 'state' thing you keep your store in. Out of curiosity, why? Your store should be its Own Thing.
I need a module to put the store; it's got to go somewhere right? Good catch! I do have state local vars all over the components file; imported store from the state module to fix.

Met48 posted:

You also need parentheses around the object you're returning, ie.

code:
const mapStateToProps = (state) => ({
        warnings: state.warnings
})
Good catch too; We're returning a dict, not two phrases connected by a colon!

Here's what it looks like now (still no work):

JavaScript code:
const WarningComp = ({ warning }) => (
    <h5>{warning.description}FROM REACT</h5>
)


const Warnings = ({ warnings }) => (
    <div>
        { warnings.map(w => <WarningComp warning={ w } />) }
    </div>
)


const mapStateToProps = (state) => (
    { warnings: state.warnings }
)


const ConnectedWarnings = connect(mapStateToProps)(Warnings)


export function run() {
    ReactDOM.render(
        <Provider store={store}>
            <ConnectedWarnings />
        </Provider>, document.getElementById('warnings'))
}
I bet it's something in the connect/mapStateToProps funcs. The Redux tutorial I linked doesn't clearly show what's actually in their store, which would help.


-geeves, that's frustrating; worth it in the long run, and that type of learning curve seems common when learning web dev, since it's uh... a web of related tools. Maybe it'll settle out in a few years, but for now, we have enough chaos to create a steep learning curve out of simple tools.

edit: Looks like the issue wasn't with connecting to react; I was using dot indexing when I needed to use .get() in the mapState func to specify which part of the store to use. :/ Will post the resulting code example once I sort through a unique key error. I gues the real learning I got out of this was that React seems much more approachable with functional components!

Is the best way to handle keys for dynamic arrays of objects/Maps to add an id field that's generated by a func to parse the array, find the highest id, and add 1?

edit: Working example code:

JavaScript code:
const WarningComp = ({ warning }) => (
    <h5>{ util.fullName(warning.person) + ' ' + warning.description }</h5>
)


const Warnings = ({ warnings }) => (
    // We use a combo of person id and category to uniquely identify the warning.
    <div>
        { warnings.map(w => <WarningComp key = { w.person.pk.toString() + w.category } 
                                         warning={ w } />) }
    </div>
)


const mapStateToProps = (state) => ({ warnings: state.get('warnings') })
const ConnectedWarnings = connect(mapStateToProps)(Warnings)


export function run() {
    ReactDOM.render(
        <Provider store={store}>
            <ConnectedWarnings />
        </Provider>, document.getElementById('warnings'))
}

Dominoes fucked around with this message at 14:01 on Apr 29, 2017

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dominoes posted:

I need a module to put the store; it's got to go somewhere right? Good catch! I do have state local vars all over the components file; imported store from the state module to fix.


My guess is this is the problem. I'll bang out a simple example tonight, but this thing you are doing putting the store inside something else is the only thing that I can possibly think of that's causing this simple example to fail. Other than a typo or something :v:


code:
export default createStore(reducer);
and

code:
import store from './myStoreFile';

<Provider store={ store }>
...
are all you need. You can just create the store right in the same file as the Provider even. It's doesn't need to "live" anywhere after that and nothing else in your app needs access to it generally.

Lumpy fucked around with this message at 15:06 on Apr 29, 2017

Dominoes
Sep 20, 2007

Lumpy posted:

My guess is this is the problem. I'll bang out a simple example tonight, but this thing you are doing putting the store inside something else is the only thing that I can possibly think of that's causing this simple example to fail. Other than a typo or something :v:
See post above; prob was using .warnings to access the warnings-reducer part of the store instead of .get('warnings'). The state import you pointed out was a bug waiting to happen, but shouldn't have affected it in this case, since the argument state would be used in all the funcs, overriding the global module import. Your functional-style's much nicer than the class-based approach I originally had; compare latest code snippet I posted to the first.

Dominoes fucked around with this message at 15:07 on Apr 29, 2017

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dominoes posted:

See post above; prob was using .warnings to access the warnings-reducer part of the store instead of .get('warnings'). The state import you pointed out was a bug waiting to happen, but shouldn't have affected it in this case, since the argument state would be used in all the funcs, overriding the global module import. Your functional-style's much nicer than the class-based approach I originally had; compare latest code snippet I posted to the first.

Ah, cool. Phone / reading posting so I missed that whole bit. Glad it's working!

necrotic
Aug 2, 2005
I owe my brother big time for this!
Dominoes, is that get accessor a new redux thing? I haven't touched it in a while but it wasn't required before!

As for dynamic collections there are a couple approaches. For small dynamic collections your approach works fine. For potentially large collection I would use a random UUID for IDs so you aren't iterating on every add. Or use a closure function for generating a scoped ID that doesn't have to iterate.

code:

function createIdGenerator() {
  let currentId = 0;
  return () => currentId++;
}

const getId = createIdGenerator();
// Calling getId gives an incremented value. Creating a new generator starts back at 1.

Dominoes
Sep 20, 2007

.get() is for when you split your store into different sections through combineReducers. Each reducer is associated with a different part of the store. It's not required if you only have one reducer. Immutable.js and the built-in Map objects use similar syntax.

The approach I posted in the example (unique combo of two values) was something I'd coincidentally been using to id things before reactifying it. Thanks for the other approach! Going to try it next time.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

necrotic posted:

Dominoes, is that get accessor a new redux thing? I haven't touched it in a while but it wasn't required before!




I just assumed he was using Immutable and didn't tell us. I have never seen / used that syntax with plain old Redux either.

Dominoes
Sep 20, 2007

Yeah - maybe it's due to using the redux-immutable combineReducers function. That example did have Immutable's combineReducers func vice the standard one.

You reminded me to try Immutable again... Got it working this time. The reducer function's cleaner now, but the .get syntax is pretty nasty, since I'm working with object (now immutable Map) nesting 3-4 layers deep. It's also confusing typescript.

JavaScript code:
warning.get('person').get('fields').get('first_name')

Dominoes fucked around with this message at 16:22 on Apr 29, 2017

necrotic
Aug 2, 2005
I owe my brother big time for this!
Oh yeah that's definitely from redux-immutable.

Roadie
Jun 30, 2013

Dominoes posted:

Yeah - maybe it's due to using the redux-immutable combineReducers function. That example did have Immutable's combineReducers func vice the standard one.

You reminded me to try Immutable again... Got it working this time. The reducer function's cleaner now, but the .get syntax is pretty nasty, since I'm working with object (now immutable Map) nesting 3-4 layers deep. It's also confusing typescript.

JavaScript code:
warning.get('person').get('fields').get('first_name')

Use reslect or similar to split your getting up into logical chunks where possible.

Dominoes posted:

It's also confusing typescript.

Make sure to mark your Immutable.js collections and map functions with the types you want to use.
JavaScript code:
Map<number, string>()
List<string>().map((s): number => parseInt(s))
Also, use Immutable.js v4 (currently 4.0.0-rc.2, final release should be soon) so that types are preserved better (e.g. things don't turn into Iterators in the middle of a chain of functions) and so you can mark types for records:
JavaScript code:
interface Point {
  x: number
  y: number
}

const Point = Record<Point>({x: 0, y: 0}, 'Point')

function whatever (param1: Record.Instance<Point>): void {
  return
}

Roadie fucked around with this message at 20:10 on Apr 29, 2017

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dominoes posted:

Yeah - maybe it's due to using the redux-immutable combineReducers function. That example did have Immutable's combineReducers func vice the standard one.



Ahhhh... the old "ask for help and don't tell us the one piece of information we needed to help you" trick. :v:

Dominoes
Sep 20, 2007

Going to play the noob-confused-by-tool-interactions-card. Surprisingly on a Q about integrating tools? ;)

Roadie posted:

Use reslect or similar to split your getting up into logical chunks where possible.


Make sure to mark your Immutable.js collections and map functions with the types you want to use.


Also, use Immutable.js v4 (currently 4.0.0-rc.2, final release should be soon) so that types are preserved better (e.g. things don't turn into Iterators in the middle of a chain of functions) and so you can mark types for records:

Cool. Looks like Immutable also has some functions designed to make nesting syntax cleaner. It still seems like you really have to commit to it... Ie switching from immutable to normal can involve indexing-syntax changes throughout the codebase.

Dominoes fucked around with this message at 10:21 on Apr 30, 2017

Dominoes
Sep 20, 2007

Yo bros: In ES2015, map and filter are Array methods. There are no comprehensions. How do you deal with generators, other than normal for loops? I want to map/filter them, but they don't have that method.

necrotic
Aug 2, 2005
I owe my brother big time for this!
It's very dumb, but you basically have to wrap the generator in an object that implements those methods.

Fortunately there's a library that looks solid for just that: https://fitzgen.github.io/wu.js/

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
All of my function calls (an now all of my function declarations) are in a $(document).ready(function() block, I've got a breakpoint on line 1 of my script, but I'm getting console output before it hits that breakpoint. How can I track this down? I don't understand how it could make any function calls before it gets to the first line of the script, much less before the DOM is loaded. I don't know how to put a breakpoint any sooner...

edit:

Oh. My. God.

It would have been really cool if my professor had ever taught me how JS actually works. The way that Java behaves asynchronously while waiting for replies from servers seems like something that would have been important to know in a web design class. Maybe just a little bit. It certainly explains why my code was breaking an unbreaking itself without me doing anything. I had no idea I had set up a race condition.

I'm so mad now. I've been tearing my hair out for 8 hours over this.

edit2: update: I now understand JS 300% more.

I wish that my introduction to this language had been more than "oh, if you want to modify something on a website, you can use some js, like this" without any real explanation of how JS functioned as a language. It seems pretty cool and powerful.

Snak fucked around with this message at 09:28 on May 4, 2017

Gul Banana
Nov 28, 2003

fyi, Java is not the same thing as Javascript (and Java does not have that kind of asynchronous loading)

Odette
Mar 19, 2011

Snak posted:

It seems pretty cool and powerful.

Heh, you say that now ... :v:

geeves
Sep 16, 2004

Snak posted:

Oh. My. God.

edit2: update: I now understand JS 300% more.

Learning the JS call stack, event loop, etc. and how they work definitely can help track down bugs or just avoid bad decisions upfront.

https://www.youtube.com/watch?v=8aGhZQkoFbQ

Newf
Feb 14, 2006
I appreciate hacky sack on a much deeper level than you.
Anyone have tips on how to make a Yeoman style cli where users can arrow themselves up and down a list to do checkbox-style selection? I'm poking around the code for Yeoman on github, but I'm finding myself following several rabbits down several holes.

As an aside, it sure would be handy if github parsed the dependencies in a package.json file to make them clickable links to npmjs/package/xyz.

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
https://www.npmjs.com/package/inquirer

Not the yeoman dependency probably but this is a pretty nice package for the question answer cli you're after.

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

Maluco Marinero posted:

https://www.npmjs.com/package/inquirer

Not the yeoman dependency probably but this is a pretty nice package for the question answer cli you're after.

Bang on, thanks. Fun fact, it actually is the Yeoman dependency, but inside of the yeoman-environment package and not at the top level.

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer

geeves posted:

Learning the JS call stack, event loop, etc. and how they work definitely can help track down bugs or just avoid bad decisions upfront.

https://www.youtube.com/watch?v=8aGhZQkoFbQ

Yeah, what was happening was I was querying a database with ajax to populate a local array, and then initializing other values from the array. When I started, this worked fine, as the secondary values were used and initialized as results of user action, I never managed to click them fast enough. . When I started automating it, they started firing before the db query had returned. Not knowing about the call stack, I was tearing my code apart trying to figure out how variables were suddenly undefined.

CodfishCartographer
Feb 23, 2010

Gadus Maprocephalus

Pillbug
So I’m making a simple clicker game in html+javascript as a fun little project. I’m trying to figure out how to get a progress bar that fills up over the course of a second, then empties and restarts. I feel like this should be easy, but I’m going insane trying to figure it out.

The relevant part of my HTML code is:
HTML code:
<progress id=“taskProg” value=“0” max=“1000”></progress>
My attempt to make it fill up over the course of a second and then stop:

JavaScript code:
function taskProg(){
	window.setInterval(function(){document.getElementByID(“taskProg”).value++;},1);
};

window.setInterval(function(){
	taskProg();
	document.getElementByID(“taskProg”).value=0;
}, 1000);
And that causes the bar to reset every second, but doesn’t fill up all the way - and then every time it resets, it fills up faster and faster and faster. I suspect it’s loading taskProg()s over and over so that’s why it fills up faster and faster, but I can’t figure out why it’s doing that and how to do it correctly. Everywhere I’ve searched online seems more concerned with making the progress bar look ~super fancy~ and I just want to get it working on a basic level first. I assume I'm doing something horribly wrong, but I can't for the life of me figure out what it is.

ROFLburger
Jan 12, 2006

Every 1000ms you're adding another taskProg interval task. After 5 seconds it'll be running 5 times as fast because 5 tasks will be incrementing the value
Either run taskProg once and control the incrementation with a flag, or in your second setInterval function, remove the the existing taskProg with clearInterval https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

E: also, running 1000 times a second may be more frequently than you actually need?

ROFLburger fucked around with this message at 22:03 on May 5, 2017

CodfishCartographer
Feb 23, 2010

Gadus Maprocephalus

Pillbug

ROFLburger posted:

Every 1000ms you're adding another taskProg interval task. After 5 seconds it'll be running 5 times as fast because 5 tasks will be incrementing the value
Either run taskProg once and control the incrementation with a flag, or in your second setInterval function, remove the the existing taskProg with clearInterval https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

E: also, running 1000 times a second may be more frequently than you actually need?

Thanks for the help, I got it working! I dunno why it never occurred to me that every second I was creating another taskProg. I wound up just removing the call for it in the second setInterval function, and just letting it run on its own, with the second one resetting the progress bar every second.

I went with 1000 because I had read that timings are based on miliseconds, so if you want something to happen every second you need to set the setInterval to 1000. I wanted the progress bar to fill up in 1 second, then reset, so I figured if I made the max 1000, and incremented it every millisecond, that'd get the job done. Is there an easier way to work at a smaller scale? I'd be perfectly fine just doing like 1/100 or something instead of having to do it 1/1000.

ROFLburger
Jan 12, 2006

I'm fairly certain that modern browsers will try to repaint every 60 times a second, so if you're updating the ratio of your progress bar 1000 times a second, the browser's going to effectively visually debounce your updates. If you want ~max performance~ out of this progress bar, updating every 17ms would probably have the same effect. This isn't a subject that I know a ton about, though.


E: window.setInterval(function(){document.getElementByID(“taskProg”).value++;},17);

ROFLburger fucked around with this message at 22:40 on May 5, 2017

necrotic
Aug 2, 2005
I owe my brother big time for this!
Use 1000/60 if you're targeting 60 fps, or look into requestAnimationFrame approaches. Note that there is no guarantee it will run that often if something else in the run loop is taking a while.

CodfishCartographer
Feb 23, 2010

Gadus Maprocephalus

Pillbug

ROFLburger posted:

I'm fairly certain that modern browsers will try to repaint every 60 times a second, so if you're updating the ratio of your progress bar 1000 times a second, the browser's going to effectively visually debounce your updates. If you want ~max performance~ out of this progress bar, updating every 17ms would probably have the same effect. This isn't a subject that I know a ton about, though.


E: window.setInterval(function(){document.getElementByID(“taskProg”).value++;},17);

I actually wound up running into another problem - it doesn't seem to update as often as it should. Even with it updating 1000 times a second, it would only fill up about a quarter of the way per second. I lowered the progress bar max to just be 250 and then it appears to be working, but I know it's not perfect and there's something wrong under the hood but again, I can't quite figure it out. I looked at the java console and it's getting to around 250ish, but moving to quickly for me to pinpoint its exact stopping spot. It feels like only one out of every 4 is actually filling up the progress bar?

necrotic
Aug 2, 2005
I owe my brother big time for this!
Something to be aware of with setInterval is there's no guarantee it will run as often as you ask, and it is also possible for two invocations to overlap (if they take too long).

With animation especially you want to use requestAnimationFrame and use some math to determine where you are in time. Let me hack up a quick example.

edit: Here you go https://jsfiddle.net/o9wtwqrp/1. Could definitely be better, but I hope this helps get you going. You can think of requestAnimationFrame(callback) as if it was setTimeout(callback, 1000/60), though they are not exactly the same.

edit2: I should add that game logic should be handled using setTimeout in a similar manner, but definitely not requestAnimationFrame. Process the game in one "thread" and then update your UI only in requestAnimationFrame.

necrotic fucked around with this message at 00:17 on May 6, 2017

geeves
Sep 16, 2004

necrotic posted:

Something to be aware of with setInterval is there's no guarantee it will run as often as you ask, and it is also possible for two invocations to overlap (if they take too long).


Yep, setInterval and setTimeout is "call this at least N milliseconds apart" There is a video I linked above that goes into all of this.

Adbot
ADBOT LOVES YOU

hooah
Feb 6, 2006
WTF?
I'm going through Stephen Grider's udemy course on React and Redux, and at one point he uses the Sparklines library to create some charts. These look fine on Chrome, but on Firefox they render enormous, and don't change size regardless of the parameters I give for height and width. Is this a known problem with Firefox, or is something else going on? Here's the JSX I'm using for a chart:

JavaScript code:
<div>
    <Sparklines height={120} width={180} data={props.data}>
        <SparklinesLine color={props.color} />
    </Sparklines>
</div>

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