On Thursday, July 20, 2017 at 10:18:00 AM UTC+2, Andrew Poulos wrote:
> I'm working on an elearning course which displays one "page" of content
> at a time to the user. Each page includes the same sort of items:.
> image, text, more text, audio...
>
> The items get displayed in sequence with various transition effects eg.
> an image fades in, text slides in from the right...
>
> What I'm finding is that some content is heavier than other content and
> so an item may display earlier/later than it should. To workaround that
> I've started putting in calls to trigger the next display eg. display
> the image when the fade in has completed display the text... rather than
> to rely on timeouts.
>
> This is ok but it's become tedious tracking stuff from within the code
> that does the transition.
Tedious is not really a sufficient reason, it's more about
manageable/understandable. Anyway, I think you are on the right track:
this is a controller, i.e. a state machine, which eventually is best
coded by tabling the states and corresponding actions/transitions.
> What I'm thinking might be a better approach is to have a "timeline"
> where there's a series of functions that get triggered by some "control"
> code. So I would have a timeline that looks like
>
> var timeline = ["a", "b", "c",...];
Rather store function references directly.
> where "a" "b" are the names of the functions to call and control code
> that looks like
>
> var position = 0;
Usually, you'd have named states, but your case might be simpler so
this might even be OK. The point really is do not get "anal" on the
patterns, what counts really is the readability/manageability of the
code, and getting there progressively.
> function runTimeline() {
> position = (position == timeline.length ? position : 0);
> window.timeline[position]();
> position++;
> }
>
> function a() {
> // do stuff and then when done
> runTimeline();
> }
> function b() {
> // do stuff and then when done
> runTimeline();
> }
Better have some driving function that calls the single actions passing a
callback... Then some would suggest promises instead of plain callbacks,
but I think that's really only appropriate for libraries/API's.
> Is that a workable approach or is there a better/smarter way?
There is always better: aim for "saves the day" to begin with.
HTH,
Julio