要求: 1、只能修改 `setTimeout` 到 `Math.floor(Math.random() * 1000` 的代码 2、不能修改 `Math.floor(Math.random() * 1000` 3、不能使用全局变量 ```javascript function print(n){ setTimeout(() => { console.log(n); }, Math.floor(Math.random() * 1000)); } for(var i = 0; i < 100; i++){ print(i); } ```
Activity
7777sea commentedon Sep 1, 2020
nameRoy commentedon Sep 1, 2020
function print(n) {
setTimeout(
Promise.resolve(n).then((n) => {
console.log(n);
}),
Math.floor(Math.random() * 1000)
);
}
for (var i = 0; i < 100; i++) {
print(i);
}
marlboroKay commentedon Sep 1, 2020
function print(n){ setTimeout(console.log(n), Math.floor(Math.random() * 1000)); } for(var i = 0; i < 100; i++){ print(i); }Jeckhenry commentedon Sep 1, 2020
function print(n) {
setTimeout(() => {
console.log(n);
}, 0, Math.floor(Math.random() * 1000));
}
for (var i = 0; i < 100; i++) {
print(i);
}
dggrok commentedon Sep 1, 2020
Cxy56 commentedon Sep 1, 2020
latte03 commentedon Sep 1, 2020
herbert-hbt commentedon Sep 1, 2020
ningtiao commentedon Sep 1, 2020
2604150210 commentedon Sep 1, 2020
gu-xiaohui commentedon Sep 1, 2020
sisterAn commentedon Sep 1, 2020
总结了一下,解法主要有三种:
方法一:
利用
setTimeout、setInterval的第三个参数,第三个以后的参数是作为第一个func()的参数传进去方法二:
修改
setTimeout第一个函数参数方法三:
利用异步函数
oukatou commentedon Nov 7, 2020
方法三错的,1000后面少了个括号
nuxio commentedon Jan 8, 2021
这。。写啥 async await哦。。
xiaowuge007 commentedon May 12, 2021
lovezzc commentedon Jul 7, 2021
方法一为什么多加一个参数就可以了
xllpiupiu commentedon Oct 5, 2021
NoBey commentedon Mar 24, 2022
异步函数 那个就是骗人, 不用 async 输出也是对的, 想到与 setTimeout(fn, 0), 宏任务也是按照顺序输出
其实方法就两种
CODZR commentedon Oct 23, 2024
借用以上代码
方法一 让执行的duration全都变成1, 与Math.floor(Math.random() * 1000)无关了
方法二 .call 立即执行函数直接把console.log执行了,与setTimeout无关了,可以通过在 return () => {} 加上console.log(n)验证