延迟Javascript

时间:2015-12-14 22:51:22

标签: javascript wordpress delay

我正在使用WordPress插件。它的一个功能是使用<span>按类隐藏和显示文本段。

这个功能有效,但是我一直希望通过让文本片段一次显示一个字母(当然很快)来加强它,就好像它们被快速输入一样,而不是一次性大量输出。

我知道有这样的动画......也许这将是一个更好的解决方案,但我一直试图保持它。但功能并不是真正的图形或动画&#34;导向;我的意图更多的是让基于文本的功能看起来更漂亮。

我已经获得了逐个字符构建每段文本的代码部分,但是我试图在每个字符之间插入一个非常短的(5-10ms)延迟,这样效果就是实际可见。我根本无法使setTimeout函数工作;有人可以给我一些建议吗?

为简单起见,我只是包含了执行此操作的文本部分;如果需要更多背景,请告诉我。以下是FOR循环,它遍历名为cols []的数组的每个元素,并按字符显示数组中的每个元素。此代码有效,但从未观察到延迟。

numberofSnippets = the size of the array cols[]

  for (c = 0; c < numberofSnippets; c++)                
      {
          h=0;
         currentshown = '';                 
         snippet = cols[c].textContent;         
         sniplength = snippet.length;           

         (function addNextCharacter()  
        {   
            onecharacter = snippet.charAt(h);
                currentshown = currentshown.concat(onecharacter);
            cols[c].textContent = currentshown;
             h=h+1;
            if (h < sniplength) {window.setTimeout(addNextCharacter, 200); }

          })();*/


          }

    }    
}        

2 个答案:

答案 0 :(得分:0)

嗯,有一个问题是你将超时设置为0,这意味着,实际上是“下一次打勾”。例如,如果你想延迟5秒,你需要在那里放5000作为第二个参数。

答案 1 :(得分:0)

你的代码中有一些奇怪的事情阻止了setTimeout按预期执行,主要是由于循环中的闭包重用变量,因为循环不会等待IIFE到用setTimeout递归执行。我通过将这些变量移动到传递给addNextCharacter的参数来解决这个问题。

&#13;
&#13;
var cols = document.getElementsByClassName('foo');
var numberofSnippets = cols.length;

for (var c = 0; c < numberofSnippets; c++) {
  (function addNextCharacter(h, c, snippet, sniplength, currentshown) {
    var onecharacter = snippet.charAt(h);
    currentshown = currentshown.concat(onecharacter);
    cols[c].textContent = currentshown;
    h = h + 1;
    if (h < sniplength) {
      setTimeout(function () {
        addNextCharacter(h, c, snippet, sniplength, currentshown);
      }, 10);
    }
  })(0, c, cols[c].textContent, cols[c].textContent.length, '');
}
&#13;
<div class="foo">Apple</div>
<div class="foo">Banana</div>
<div class="foo">Orange</div>
<p class="foo">There were a few oddities in your code that was preventing the setTimeout from performing as expected, mostly due to the closure reusing variables within the loop due to the fact that the loop isn't going to wait for the IIFE to finish recursively executing with a setTimeout. I solved that by moving those variables to parameters passed to addNextCharacter.</p>
&#13;
&#13;
&#13;

这里是强制性的.forEach版本,它避免了需要将变量作为参数传递。

var cols = document.getElementsByClassName('foo');
var numberofSnippets = cols.length;

[].forEach.call(cols, function(el) {
  var snippet = el.textContent;
  var sniplength = snippet.length;
  var currentshown = '';
  (function addNextCharacter(h) {
    var onecharacter = snippet.charAt(h);
    currentshown = currentshown.concat(onecharacter);
    el.textContent = currentshown;
    h = h + 1;
    if (h < sniplength) {
      setTimeout(function() {
        addNextCharacter(h);
      }, 1000);
    }
  })(0);
});