Skip to content

Instantly share code, notes, and snippets.

@mcattx
Created March 28, 2017 16:45
Show Gist options
  • Save mcattx/bb4799d33179ce9d539980e3367758cf to your computer and use it in GitHub Desktop.
Save mcattx/bb4799d33179ce9d539980e3367758cf to your computer and use it in GitHub Desktop.
如何使用定时器settimeout、setInterval执行传递参数的函数
function fn(isPause) {
// isPause: Boolean;
if(isPause) {
// your codes here
} else {
}
}
// normally, fn will be called immediately.
setTimeout(fn(isPause), 2000);
// Here are some tricks
// Trick 1:
// This is bad. Not recommended! Beacuse JS will call eval() in setTimtou();
window.setTimeout("fn(isPause)", 2000);
// Trick 2:
function _fn(isPause) {
return function() {
fn(isPause);
}
}
setTimeout(fn(isPause), 2000);
// Trick 3:
// Modify [Native Object] is Not recommended, either.
var preSetInterval = window.setInterval;
window.setInterval = function(callback,timeout,param){
var args = Array.prototype.slice.call(arguments,2);
var _cb = function(){
callback.apply(null,args);
}
preSetInterval(_cb,timeout);
}
window.setInterval(fn, 2000, isPause);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment