为什么用setInterval不能重复运行,用setTImeout加原函数就可以重复运行呢?

  1. var j = 0;
    function bubbleSort() {

       Timer = setInterval(function()
       {
           if (data.length - 1 < 1) {
               clearInterval(Timer);
           };
           if (data[j] > data[j + 1]) {
               var swap = data[j];
               data[j] = data[j + 1];
               data[j + 1] = swap;
               console.log(j);
               show();
           };
    
           if (j == data.length-2) {
               j = 0;
           } else {
               j++;
           };
       }, 2);

    }

  2. var j = 0;

    function bubbleSort() {

       Timer = setTimeout(function()
       {
           if (data.length - 1 < 1) {
               clearTimeout(Timer);
           };
           if (data[j] > data[j + 1]) {
               var swap = data[j];
               data[j] = data[j + 1];
               data[j + 1] = swap;
               console.log(j);
               show();
           };
           if (j == data.length-2) {
               j = 0;
           } else {
               j++;
           };
           bubbleSort()
       }, 2);

    }

阅读 4.4k
3 个回答

你执行bubbleSort()了吗

间隔2ms?

该不会是没反应过来就排完了吧

if (data.length - 1 < 1) {
   clearInterval(Timer);
};

如果data.length<=1,interval定时器将被清除,定时器回调函数没有机会被再次执行

if (data.length - 1 < 1) {
   clearTimeout(Timer);
};

如果data.length<=1,timeout定时器也被清除,但是回调函数最后又调用了bubbleSort(),又会设置新的timeout定时器,重复又重复~~~

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