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 & setInterval 语法 #70

Open
leeenx opened this issue Sep 15, 2017 · 1 comment
Open

setTimeout & setInterval 语法 #70

leeenx opened this issue Sep 15, 2017 · 1 comment

Comments

@leeenx
Copy link
Contributor

leeenx commented Sep 15, 2017

用了几十年的这两个函数,其实我并不知道它们的完全语法是怎么样的。今天特意查了一下 MDN:

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/setTimeout
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/setInterval

setTimeout

有两种语法:
var timeoutID = setTimeout(function[, delay, param1, param2]);
var timeoutID = setTimeout(function[, delay]);
var timeoutID = setTimeout(code[, delay]);

第一种语法可以看作是第二种语法的完全格式?
理论上说是这样的,不过 IE9及更早的浏览器不支持第一种语法。所以这里第一和第二算作两种语法。

第三种语法中的 code 其实是一段字符串,setTimeout 在执行它的时候自动调用 eval。如下:

setTimeout("console.log('haha')");
// haha
第三种语法不推荐使用。

第一种语法后面的 param1, param2, ... 是做什么的?
其实,param1, param2, ... 会被传递给 function 作为它的实参。如下:
setTimeout(function cb() {console.log("形参列表的长度:", cb.length, "实参列表的长度:", arguments.length)}, 0, 1, 2, 3, 4)
// 形参列表的长度: 0 实参列表的长度: 4

然而第一种语法一般没人用,属于生僻用法。为什么呢?
如果需要传参,我一般会再套一层 function。如下:
function func() {console.log("形参列表的长度:", func.length, "实参列表的长度:", arguments.length)};
setTimeout(function cb() {
func(1, 2, 3, 4)
}, 0)
// 形参列表的长度: 0 实参列表的长度: 4

setInterval

与 setTimeout 一样有三种语法,如下:
var intervalID = setInterval(function, delay[, param1, param2]);
var intervalID = setInterval(function, delay);
var intervalID = setInterval(code, delay);

setInterval 的 delay 是必选项。其实的问题与 setTimeout 一样。

@h5m1007
Copy link

h5m1007 commented Oct 15, 2018

受教知识点:

  1. 形参、实参
  2. 形参长度,实参长度

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants