Skip to content

Instantly share code, notes, and snippets.

@zhanhongtao
Last active December 23, 2015 07:49
Show Gist options
  • Save zhanhongtao/6603650 to your computer and use it in GitHub Desktop.
Save zhanhongtao/6603650 to your computer and use it in GitHub Desktop.
/*
@return {object}
{
on: 开权限
off: 取消权限
done: 有权限时, 执行操作
}
*/
function create( func, check, time ) {
var flag = false;
var hasDone = false;
var timer;
var done = function( array ) {
func.apply( this, array );
hasDone = true;
if ( time == null ) {
reset();
}
};
var reset = function() {
if ( timer ) {
clearTimeout( timer );
timer = null;
}
flag = hasDone = false;
};
if ( typeof check != 'function' ) {
var old = check;
check = function () {
return !!old;
};
}
return {
on: function() {
if ( !flag && check.apply(this, arguments) ) {
flag = true;
if ( typeof time == 'number' && time > 0 )
timer = setTimeout( reset, time * 1000 );
}
return this;
},
off: function( callback ) {
if ( hasDone || time == null ) {
if ( typeof callback == 'function' ) {
callback();
}
}
reset();
return this;
},
done: function() {
if ( flag && !hasDone ) {
done( [].slice.call(arguments) );
}
return this;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment