我需要一个不是setTimeout()的延迟

时间:2016-08-06 16:39:02

标签: javascript jquery function delay

这是我拥有的代码,我希望它能够使字母(句子参数)逐个输入。不是一次一个。我一直在尝试使用setTimeout(),但我不能这样做,以便它保持它的进展。请帮忙。

var letters = [];

function typeOut(sentence, code) {
    $('body').append('<p id=' + code + '></p>');


    for (i = 0; i < sentence.length; i++) {
        letters[i] = sentence[i];
        $('#' + code).append(letters[i]);
    }
}

typeOut("Hello World", 1);

提前致谢!

5 个答案:

答案 0 :(得分:3)

setTimeout似乎很完美。我猜你用的不对。

function typeOut(sentence) {
  var txt = document.body
    .appendChild(document.createElement('p'))
    .appendChild(document.createTextNode(''));
  var i = 0;
  (function typeLetter() {
    if(i < sentence.length) {
      txt.nodeValue += sentence[i];
      ++i;
      setTimeout(typeLetter, 100);
    }
  })();
}
typeOut("Hello World");

答案 1 :(得分:0)

有很多方法可以让这项工作可以解决这个问题

 var letters = [];

function typeOut(sentence, code) {
    $('body').append('<p id=' + code + '></p>');
    self = this;
    self.currentIndex = 0;
    self.sentence = sentence;
    
	  var write =  function (){
    	if(self.currentIndex < sentence.length) {
          letter = sentence[self.currentIndex];
          $('#' + code).append(letter);
           self.currentIndex+=1;
    	}else {
          clearInterval(self.writeHandler);
        }
    }
    
    self.writeHandler = setInterval(write, 500)
}

typeOut("Hello World", "div1");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p id="div1"></p>

这里是jsbin check this

答案 2 :(得分:0)

我对这个问题很开心.... 我可能比你提出的要多一点 但我想你会喜欢它。

this CodePen

我的typeOut功能版本:

function typeOut(sentence, code) {
    $('body').append('<p id=' + code + '></p>');

    var i=0;
    var letterDelay = setInterval(function(){
        $('#' + code).append(sentence[i]);
        i++;
    }, $("#speed").val() );
}

答案 3 :(得分:0)

确实没有那么多选项,唯一适用的是定时器,setTimoutsetInterval

你总是可以使用jQuery的delay()方法,但在内部它也使用setTimeout

&#13;
&#13;
function typeOut(sentence, speed) {
    var p = $('<p />'), i = 0;
    $('body').append(p);
    
    (function go() {
        p.dequeue().append(sentence[i++]).delay(speed).queue(go);
    })();
}

typeOut("Hello World", 1000);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

为什么没有人记得setTimeout接受两个以上的论点?这是非常方便的功能。这是我的typeOut版本。

&#13;
&#13;
function typeOut(text) {
    var out = document.getElementById('out');
    out.innerHTML = '';
    setTimeout(function typeNext(i) { //internal function can be named
        out.innerHTML += text[i++];
        if (i < text.length)
            setTimeout(typeNext, 100, i);
    }, 100, 0); //3rd arg goes to the function
}
&#13;
<p id="out"></p>
<button type="button" onclick="typeOut('Hello World');">Type Out</button>
&#13;
&#13;
&#13;