Skip to content

Instantly share code, notes, and snippets.

@DavidBruant
Created November 13, 2012 15:39
Show Gist options
  • Save DavidBruant/4066406 to your computer and use it in GitHub Desktop.
Save DavidBruant/4066406 to your computer and use it in GitHub Desktop.
Figure out max vibration value
"use strict";
(function(global){
if(typeof global.navigator.vibrate === 'function')
return;
var MAX = Math.floor(1000000*Math.random());
console.log('MAX', MAX);
global.navigator.vibrate = function vibrate(time){
if(time === 0){
console.log('vibrate canceled!')
return;
}
if(time > MAX)
throw new Error('I cannot vibrate for that long, dude!');
console.log('vibrating for '+time+' ms', 'br'+Array(Math.floor(Math.log(time))).join('r'))
}
})(this);
(function(){
function tryVibrationTime(t){
var vibrate = navigator.vibrate.bind(navigator);
try{
vibrate(t);
vibrate(0); // cancelling the vibration to not annoy the user.
// it worked since no error was thrown
return true;
}
catch(e){ // oops, tried to vibrate for too long
return false;
}
}
function figureOutVibrationLimit(){
var vibrateMin = 1;
var vibrateMax;
var attempt;
while(vibrateMax === undefined && attempt !== Infinity){
attempt = vibrateMin*2;
if(tryVibrationTime(attempt))
vibrateMin = attempt;
else
vibrateMax = attempt;
}
if(attempt === Infinity)
return Infinity;
// now we know the value is between vibrateMin and vibrateMax. DICHOTOMY!!!
while(vibrateMax - vibrateMin > 1){
attempt = Math.floor( (vibrateMin+vibrateMax)/2 );
if(tryVibrationTime(attempt))
vibrateMin = attempt;
else
vibrateMax = attempt;
}
return vibrateMin;
}
console.log(figureOutVibrationLimit());
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment