【问题标题】:Where is the loop?循环在哪里?
【发布时间】:2020-06-18 21:31:32
【问题描述】:

我有这段代码可以为我的网页创建一个打字轮播效果。我正在尝试使轮播在到达数组中的最后一个字符串时停止。但是我无法找到无限循环的位置?

由于没有 while 或 for 循环,我很困惑这甚至是如何重复的。谁能给我指点?

var TxtRotate = function(el, toRotate, period) {
  this.toRotate = toRotate;
  this.el = el;
  this.loopNum = 0;
  this.period = parseInt(period, 10) || 2000;
  this.txt = '';
  this.tick();
  this.isDeleting = false;
  return;
};

TxtRotate.prototype.tick = function() {
  var i = this.loopNum % this.toRotate.length;
  var fullTxt = this.toRotate[i];

  if (this.isDeleting) {
    this.txt = fullTxt.substring(0, this.txt.length - 1);
  } else {
    this.txt = fullTxt.substring(0, this.txt.length + 1);
  }

  this.el.innerHTML = '<span class="wrap">' + this.txt + '</span>';

  var that = this;
  var delta = 80;

  if (this.isDeleting) {
    delta /= 2;
  }

  if (!this.isDeleting && this.txt === fullTxt) {
    delta = this.period;
    this.isDeleting = true;
  } else if (this.isDeleting && this.txt === '') {
    this.isDeleting = false;
    this.loopNum++;
    delta = 200;
  }

  setTimeout(function() {
    that.tick();
  }, delta);
};

window.onload = function() {
  var elements = document.getElementsByClassName('txt-rotate');
  var toRotate = elements[0].getAttribute('data-rotate');
  var period = elements[0].getAttribute('data-period');
  if (toRotate) {
    new TxtRotate(elements[0], JSON.parse(toRotate), period);
  }
  // INJECT CSS
  var css = document.createElement("style");
  css.type = "text/css";
  css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }";
  document.body.appendChild(css);
  return;
};

【问题讨论】:

  • 这样的“循环”是通过setTimeout调用调用setTimeout的函数来启用的。

标签: javascript html loops


【解决方案1】:

它使用某种可以自行“倒带”的时钟。

tick的结尾是这样的:

  setTimeout(function() {
    that.tick();
  }, delta);

表示当函数tick结束时,它会安排自己在delta时间之后再次调用。

如果您不熟悉这个(非常有用的)JavaScript 函数,请参阅setTimeout documentation

如果你想让它停止重复,只需将上面的行用你的延续条件包装在一个 if 块中,你就可以开始了。

第一次调用tick 发生在构造函数中创建对象 TxtRotate 时。

【讨论】:

  • 啊,有道理!如果满足某个条件,有没有办法不调用下一个刻度?
  • 安排下一次通话的是setTimeout。只需将该调用(我在答案中复制的行)包装在某个 if 块中,您就有了结束条件!