Skip to content

Instantly share code, notes, and snippets.

@jpreece6
Forked from leecrossley/shake.js
Last active August 29, 2015 13:58
Show Gist options
  • Save jpreece6/10397220 to your computer and use it in GitHub Desktop.
Save jpreece6/10397220 to your computer and use it in GitHub Desktop.
Shake.js edited for better error handling. Using a shake.error() function which can be overridden with an external function.
var shake = (function () {
var shake = {},
watchId = null,
options = { frequency: 300 },
previousAcceleration = { x: null, y: null, z: null },
shakeCallBack = null;
// Start watching the accelerometer for a shake gesture
shake.startWatch = function (onShake) {
if (onShake) {
shakeCallBack = onShake;
}
if (navigator.accelerometer !== undefined) {
watchId = navigator.accelerometer.watchAcceleration(getAccelerationSnapshot, shake.error, options);
} else {
shake.error("Accelerometer Not Supported!");
}
};
// Stop watching the accelerometer for a shake gesture
shake.stopWatch = function () {
if (watchId !== null) {
navigator.accelerometer.clearWatch(watchId);
watchId = null;
}
};
// Handle errors. Can be overridden with external function
shake.error = function(msg) {
console.error("Shake - " + msg);
};
// Gets the current acceleration snapshot from the last accelerometer watch
function getAccelerationSnapshot() {
navigator.accelerometer.getCurrentAcceleration(assessCurrentAcceleration, shake.error);
}
// Assess the current acceleration parameters to determine a shake
function assessCurrentAcceleration(acceleration) {
var accelerationChange = {};
if (previousAcceleration.x !== null) {
accelerationChange.x = Math.abs(previousAcceleration.x, acceleration.x);
accelerationChange.y = Math.abs(previousAcceleration.y, acceleration.y);
accelerationChange.z = Math.abs(previousAcceleration.z, acceleration.z);
}
if (accelerationChange.x + accelerationChange.y + accelerationChange.z > 30) {
// Shake detected
if (typeof (shakeCallBack) === "function") {
shakeCallBack();
}
shake.stopWatch();
setTimeout(shake.startWatch, 1000);
previousAcceleration = {
x: null,
y: null,
z: null
}
} else {
previousAcceleration = {
x: acceleration.x,
y: acceleration.y,
z: acceleration.z
}
}
}
return shake;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment