Skip to content

Instantly share code, notes, and snippets.

@bga
Created September 24, 2010 12:49
Show Gist options
  • Save bga/595299 to your computer and use it in GitHub Desktop.
Save bga/595299 to your computer and use it in GitHub Desktop.
// (C) new BSD license
// fix FF bug (delay pass to function) and add support of arguments
(function($G)
{
var fnCache = {};
var _fixNoArgs = function(_origFn, _arraySlice)
{
return function(/*_fn, delay*/) // .length === 0
{
if(arguments.length <= 2)
{
return _origFn(arguments[0], arguments[1] || 0);
}
else
{
var _fn = arguments[0];
if(_fn === '') // chrome behavior
return;
if(typeof(_fn) != 'function')
{
_fn += ''; // to string
_fn = fnCache[_fn] || (fnCache[_fn] = new Function(_fn));
}
var args = _arraySlice.call(arguments, 2);
return _origFn(
function()
{
_fn.apply($G, args)
},
arguments[1] || 0
);
}
};
};
var _fixFFBug = function(_origFn, _arraySlice)
{
return function(/*_fn, delay*/) // .length === 0
{
if(arguments.length <= 2)
{
var _fn = arguments[0];
if(_fn === '') // chrome behavior
return;
if(typeof(_fn) != 'function')
{
_fn += ''; // to string
_fn = fnCache[_fn] || (fnCache[_fn] = new Function(_fn));
}
return _origFn(
function()
{
_fn.call($G);
},
arguments[1] || 0
);
}
else
{
return _origFn.apply($G, arguments);
}
};
};
var _fixNoArgsAndFFBug = function(_origFn, _arraySlice)
{
return function(/*_fn, delay*/) // .length === 0
{
var _fn = arguments[0];
if(_fn === '') // chrome behavior
return;
if(typeof(_fn) != 'function')
{
_fn += ''; // to string
_fn = fnCache[_fn] || (fnCache[_fn] = new Function(_fn));
}
if(arguments.length <= 2)
{
return _origFn(
function()
{
_fn.call($G);
},
arguments[1] || 0
);
}
else
{
var args = _arraySlice.call(arguments, 2);
return _origFn(
function()
{
_fn.apply($G, args)
},
arguments[1] || 0
);
}
};
};
var _testAndFix = function(setFnName, clearFnName)
{
var id = $G[setFnName](
function(a, b, c)
{
$G[clearFnName](id);
var noArgs = a !== 1 || b !== '2' || c !== true;
var id = $G[setFnName](
function(a)
{
$G[clearFnName](id);
var ffBug = arguments.length > 0;
var _fixer;
if(ffBug && noArgs)
_fixer = _fixNoArgsAndFFBug;
else if(ffBug)
_fixer = _fixFFBug;
else if(noArgs)
_fixer = _fixNoArgs;
if(_fixer)
$G[setFnName] = _fixer($G[setFnName], [].slice);
},
0
);
},
0,
1, '2', true
);
};
_testAndFix('setTimeout', 'clearTimeout');
_testAndFix('setInterval', 'clearInterval');
})(this);
(function($G)
{
// test
$G.setTimeout(
function()
{
$G.setTimeout(
function(a, b, c)
{
console.log('args test', a === 1 && b === '2' && c === true);
},
0,
1, '2', true
);
$G.setTimeout(
function()
{
console.log('ff bug test', arguments.length == 0);
},
0
);
},
1000
);
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment