惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
C
Cisco Blogs
Scott Helme
Scott Helme
Know Your Adversary
Know Your Adversary
NISL@THU
NISL@THU
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Schneier on Security
I
Intezer
Spread Privacy
Spread Privacy
AWS News Blog
AWS News Blog
V
Vulnerabilities – Threatpost
Cloudbric
Cloudbric
V2EX - 技术
V2EX - 技术
Google Online Security Blog
Google Online Security Blog
L
Lohrmann on Cybersecurity
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LINUX DO - 热门话题
S
Secure Thoughts
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
Recent Announcements
Recent Announcements
Security Archives - TechRepublic
Security Archives - TechRepublic
Stack Overflow Blog
Stack Overflow Blog
罗磊的独立博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
K
Kaspersky official blog
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Latest news
Latest news
B
Blog
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
L
LangChain Blog
GbyAI
GbyAI
Last Week in AI
Last Week in AI
S
Security Affairs
Apple Machine Learning Research
Apple Machine Learning Research
N
Netflix TechBlog - Medium
Security Latest
Security Latest
Vercel News
Vercel News
Y
Y Combinator Blog
G
GRAHAM CLULEY
S
Securelist
T
Troy Hunt's Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
雷峰网
雷峰网

博客园 - 三聪

流操作 如何利用.Net内置类,解析未知复杂Json对象 制作等比环切缩缩图 利用NewID()生成随机数 创建缩略图 winform给html提供接口 IE下记住文本框的光标位置 ie下取得iframe里面内容 短网址计算 树冲突 截图片 学习Objective-C: 入门教程 C#根据字节数截取字符串 asp.net本地和全局资料文件的读取方法 jquery实现点击空白的事件 Asp.net 利用Jquery Ajax传送和接收DataTable 用一个最简单方法解决asp.net页面刷新导致数据的重复提交 SOS"未将对象引用设置到对象的实例" .NET调PHP Web Service的典型例子
让window.setTimeout等支持带参数方法
三聪 · 2013-02-19 · via 博客园 - 三聪

在写js时经常会使用到无参或固定参数方法,比如window.setTimeout(func,300) 比如$("input").click(func)等

如果我们需要定时执行的一个参多个参数方法,应该如果处理呢?

比如有这样一个方法:

function log(a, b){
  console.log(a + "_" + b);
}

我们需要定时400毫秒后执行

直接用log方法是行不通的:

window.setTimeout(log,100); //错误的

我们首先想到可行的方法:

window.setTimeout(function(){log(1,2)},100);

再来一个复杂点的例子,先看一个槽糕的写法:

for ( var i = 0; i < 20; i++) {
    window.setTimeout( function () {
        log(i,i+1);
    }, 100);
}    

这样每次出来的结果都是20_21

正确的写法

for ( var i = 0; i < 20; i++) {
    window.setTimeout( function (a,b) {
        return function () { log(a,b); };
    }(i,i+1), 100);
}    

如果觉得这样写比较复杂,可以用更通用的方式
可以为Function扩展一个方法,专门用来返回一个无参方法

Function.prototype.curry = function () {
    var slice = Array.prototype.slice,
        args = slice.apply(arguments),
        that = this ;
    return function () {
        return that.apply(null , args.concat(slice.apply(arguments)));
    };
};

上面的方法就可以简化为:

for ( var i = 0; i < 20; i++) {
    window.setTimeout(log.curry(i,i+1), 100);
}

实例代码