重复调用一个函数,怎么让其按序执行?

<script>
  test()
  test()
  test()
  function test(){
    setTimeout(function () {
      console.log('test')
    },2000)
  }`请输入代码`
</script>

2000毫秒秒后同时打印,怎么才能每隔2000毫秒打印一次

阅读 4.2k
7 个回答
run()

function test(sleep, callback) {
    return new Promise(resolve => setTimeout(() => {
        callback();
        resolve();
    }, sleep))
}

async function run() {
    await test(2000, () => console.log('test'))
    await test(2000, () => console.log('test'))
    await test(2000, () => console.log('test'))
}

可以用闭包的,比如

//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()

你写三个函数输出不一样再试试

setInterval(function(){
console.log('text')
},2000}

  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);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题