<script>
test()
test()
test()
function test(){
setTimeout(function () {
console.log('test')
},2000)
}`请输入代码`
</script>
2000毫秒秒后同时打印,怎么才能每隔2000毫秒打印一次
<script>
test()
test()
test()
function test(){
setTimeout(function () {
console.log('test')
},2000)
}`请输入代码`
</script>
2000毫秒秒后同时打印,怎么才能每隔2000毫秒打印一次
可以用闭包的,比如
//number:运行次数
function getFn (number){
return function test(){
var fn = arguments.callee;
var time = setTimeout(function () {
if (number<=0){ clearTimeout(time);return};
fn()
console.log('test--'+number)
number--;
},2000)
}
}
var fns = getFn(3)
fns()
test(2000)
test(4000)
test(6000)
function test(time){
setTimeout(function () {
console.log('test')
},time)
}
在不改变题目使用方式的情况下,需要引入全局的缓冲池,这里做简单的计数即可。
test()
test()
test()
function test(){
if ((window[Symbol.for('__test__')] = (window[Symbol.for('__test__')] || 0) + 1) === 1) {
_fn()
}
function _fn () {
setTimeout(function () {
console.log('test')
if (--window[Symbol.for('__test__')]) {
_fn()
}
}, 2000)
}
}
(function($loop, $timeout){
function test(){
console.log('test ['+$loop+']');
if(--$loop > 0)
setTimeout(test, $timeout);
}
setTimeout(test, $timeout)
})(3, 2000);
13 回答12.8k 阅读
7 回答2k 阅读
3 回答1.1k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
6 回答918 阅读✓ 已解决
6 回答1.1k 阅读
2 回答1.3k 阅读✓ 已解决