Created
March 28, 2017 16:45
-
-
Save mcattx/bb4799d33179ce9d539980e3367758cf to your computer and use it in GitHub Desktop.
如何使用定时器settimeout、setInterval执行传递参数的函数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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