Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Other Christmas story with Santa sleigh progress bar Reply To: Christmas story with Santa sleigh progress bar

#248713
Shikkediel
Participant

I’ve been confusing the terms throttle and debounce before as well and ended up reading that exact article. Nothing like an explanation by Chris to make things clear. The lean functions you are using for it are quite excellent, I also think a larger plugin for it is usually overkill.

Although I’ve had some wonderful moments of expanding insight in JS, I often still feel like a complete amateur. Scratching my head at very basic stuff… but much can be learned from the true wizards, like the use of that global object wrapper which is what jQuery does. But instead of window.vial they use window.jQuery.

Going for that approach is mostly useful when you want to share functions and variables across scripts. Normally one would then create them all globally so the functions in each script can access them. But that clutters the (global) window object. So instead only a single global object wrapper is created as a container for all the global stuff.

As I’m still working on the concept, I don’t have much of a live demo to look at yet. But I can show another example of a function I can add besides the throttling function, which is feature testing (one’s own little Modernizr). So I would add this to the script above:

vial.abide = (function() {

  return [
  history.replaceState != 'undefined',
  typeof SVGRect != 'undefined'
  ];
})();

After execution vial would look something like this:

{
restrain: function(delay, callback) { ... },
abide: [true,true]
}

Besides a function to throttle events that I can use globally, there’s now also an array with info I can access to conditionally execute an action in another script based on the feature test. For example, if I want to animate an SVG I can check if it’s supported first:

if (vial.abide[1] == true) { // do some SVG things }

Or shorter:

if (vial.abide[1]) { // do some SVG things }

As mentioned before, it is not only handy to communicate between scripts but also convenient when using anonymous functions anywhere. All variables would then be limited to the scope of the function itself… but the data inside the global object are still accessible:

var svgsupport  = true;

(function() {

  if (svgsupport) // can't be reached

  if (vial.abide[1]) // but this one can
})();

It probably depends on the use case if creating this global object is beneficial. It would often be a balance between firing another server request for a separate script or rereading functions inside scripts where a common source could be used. Obviously jQuery is large enough to make a link of it’s own for it. But seeing you’ve written somewhat of a library yourself it might start to be convenient at some point, Beverley.

:-)