在循环中 2 秒后添加 class 并在 7 秒后删除

Add class after 2 second and remove after 7 second in loop

我想在 2 秒后添加一个 class 并在 7 秒后将其删除,当再次删除时在 2 秒后添加 class 并在 7 秒后删除它

$(document).ready(function() {
    function removeAddClass1() {
      $(".video_title").removeClass("level_show");
      setTimeout(removeAddClass1, 7000);
    }
    removeAddClass1();

    function removeAddClass2() {
      $(".video_title").addClass("level_show");
      setTimeout(removeAddClass2, 2000);
    }
    removeAddClass2();
});
.video_title {
  color: red;
}
.video_title.level_show {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="video_title">Video title</h2>

我建议为此使用 CSS 关键帧:

.video_title {
  color: red;
  animation: levelshow 7000ms infinite;
}

@keyframes levelshow {
  29.9% {
    color: red;
  }
  30% {
    color: green;
  }
  99.9% {
    color: green;
  }
  100% {
    color: red;
  }
}
<h2 class="video_title">Video title</h2>

这是 JavaScript 的一种方法:

window.onload = () => {
  document.querySelector(".video_title").classList.remove("level_show")
  toggleSequence()
  setInterval(toggleSequence, 7000);
}

function toggleSequence() {
  setTimeout(() => {
    document.querySelector(".video_title").classList.toggle("level_show");
  }, 2000)
  setTimeout(() => {
    document.querySelector(".video_title").classList.toggle("level_show");
  }, 7000)
}
.video_title {
  color: red;
}

.video_title.level_show {
  color: green;
}
<h2 class="video_title">Video title</h2>

这是由 javascriptjQuery 完成的,没有使用 CSS keyframes

// for switch class
const switchCls = (selector, cls) => $(selector).toggleClass(cls);

// delay and do task
const delay = (action, ms) => {
  return new Promise((resolve) => {
    const newAction = () => {
      action();
      resolve(action);
    };
    setTimeout(newAction, ms);
  });
};

// ensure execution order
const task = (selector, cls) => {
  const switchFn = () => switchCls(selector, cls);
  delay(switchFn, 2000).then(action =>
    delay(action, 7000)
  ).then(action =>
    task(selector, cls)
  );
};

// start execution
task('.video_title', 'level_show');

// screen timer
let second = 0;
setInterval(() => {
  $('h1').text(`${++second} second`);
}, 1000);
.video_title {
  color: red;
}

.video_title.level_show {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 class="video_title">Video title</h2>
<h1>0 second</h1>