使用带按钮的setTimeout()方法停止并重启功能

问题描述 投票:1回答:2

我创建了一个从数组中选择颜色以更改背景颜色的函数。访问后,从数组中选择将重新启动。然后我在<body>元素中添加了两个按钮来停止并重新启动颜色拾取,我希望函数在我选择“重启”按钮时按下“停止”按钮的点继续拾取颜色。我试过这种方式,但它从数组的第一个元素重新启动:

$(document).ready(() => {
    const colors = ['blue','red','yellow','green'];
    let loop;
    function start(i){
      if(i < colors.length){
        loop = setTimeout(function(){
          $('body').css("backgroundColor", colors[i]);
          i++;
          if (i >= colors.length) {
            i = 0;
          }
          start(i);
        }, 1000);
      }
    }

    $('#btnStop').on('click', () => {
      clearTimeout(loop);
    });

    $('#btnRestart').on('click', () => {
      loop = start(0);
    });

    start(0);
  })
javascript jquery css
2个回答
0
投票

你可以通过添加另一个变量来实现

$(document).ready(() => {
    const colors = ['blue','red','yellow','green'];
    let loop;
    var iNUM = 0; //<<<<<<<<<<<
    function start(i){
      if(i < colors.length){
        loop = setTimeout(function(){
          $('body').css("backgroundColor", colors[i]);
          i++;
          if (i >= colors.length) {
            i = 0;
          }
          iNUM = i; //<<<<<<<<<<
          start(i);
        }, 1000);
      }
    }

    $('#btnStop').on('click', () => {
      clearTimeout(loop);
    });

    $('#btnRestart').on('click', () => {
      start(iNUM); //<<<<<<<
    });

    start(0);
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnStop">Stop</button>
<button id="btnRestart">Start</button>

0
投票

Array.shift()Array.push()怎么样?

const colors = ['blue', 'red', 'yellow', 'green'];
console.log(colors[0]);
colors.push(colors.shift());
console.log(colors[0]);
© www.soinside.com 2019 - 2024. All rights reserved.