Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

重写setTimeout方法 #57

Open
spring-fe opened this issue Jan 12, 2019 · 0 comments
Open

重写setTimeout方法 #57

spring-fe opened this issue Jan 12, 2019 · 0 comments

Comments

@spring-fe
Copy link
Owner

spring-fe commented Jan 12, 2019

重写setTimeout方法
新的方法为: setTimeout(callback,delay,params)
参数:callback为回调函数,delay为延迟时间,params为callback传入的参数值。

方法一:使用高阶函数

function overrideSetTimeout (fn) {
    return function (callback, delay, params) {
        var args = Array.prototype.slice.call(arguments, 2);
        var _callback = function() {
             callback.apply(null, args);
        }
        fn(_callback, delay);
    }
}
setTimeout = overrideSetTimeout(setTimeout);
setTimeout(function(a, b) {
    alert(a + '' + b);
}, 1000, 'a', 'b');

不能直接在overrideSetTimeout方法内直接使用原生的setTimeout,这样会无穷尽调用复写的setTimeout。如下所示:

function overrideSetTimeout(){
  return function(callback, delay, params){
    setTimeout(callback.bind(null,params),delay);
  }
}
setTimeout = overrideSetTimeout();
setTimeout(function(params){
  alert(params)
},1000,'a')

方法二:使用中间变量origin

var origin = setTimeout;
setTimeout = function(callback, delay, params){
    var args = Array.prototype.slice.call(arguments, 2);
    function _callback(){
        callback.apply(null, args);
    }
    origin(_callback,delay);
}

setTimeout(function(a,b){
    alert(a + '' +b);
},1000,'a', 'b');
@spring-fe spring-fe changed the title 重写setTimeout 重写setTimeout方法 Jan 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant