Skip to content

Instantly share code, notes, and snippets.

@wrannaman
Last active August 29, 2015 14:22
Show Gist options
  • Save wrannaman/f608461efec030baf13b to your computer and use it in GitHub Desktop.
Save wrannaman/f608461efec030baf13b to your computer and use it in GitHub Desktop.
Useful JS Helper Functions
// Try with scroll, resize, key up/down/etc
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// Usage
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
}, 250);
window.addEventListener('resize', myEfficientFn);
// function can only fire once
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
// Get absolute URL
var getAbsoluteUrl = (function() {
var a;
return function(url) {
if(!a) a = document.createElement('a');
a.href = url;
return a.href;
};
})();
// Usage
getAbsoluteUrl('/something');
// returns http://andrewpierno.com/something
// Check for desired state by polling
function poll(fn, callback, errback, timeout, interval) {
var endTime = Number(new Date()) + (timeout || 2000);
interval = interval || 100;
(function p() {
// If the condition is met, we're done!
if(fn()) {
callback();
}
// If the condition isn't met but the timeout hasn't elapsed, go again
else if (Number(new Date()) < endTime) {
setTimeout(p, interval);
}
// Didn't match and too much time, reject!
else {
errback(new Error('timed out for ' + fn + ': ' + arguments));
}
})();
}
// Usage: ensure element is visible
poll(
function() {
return document.getElementById('lightbox').offsetWidth > 0;
},
function() {
// Done, success callback
},
function() {
// Error, failure callback
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment