本文介绍了在内部以设置的间隔循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个字母一个字母地写文本,并暂停3秒钟.之间.

I need to write a text one by one letter, with pausing 3 sec. between.

我尝试了此操作,但不起作用. 3秒后.整个文本一次写完.

I tried this but doesn't work. After 3 sec. entire text is written at once.

function thanks() {   
    $("#writer").text("");
    var txt = "Thanks for visiting !";

    for ( var i = 0; i < 22; i++) {
      setInterval(function(){
        var type = txt.substring(0, i);
        $("#writer").text(type);
      }, 3000);
    };
};

推荐答案

您一次要排队22个电话,所有电话都在3秒后发生.只需创建一次间隔,每次调用都会输出新文本.当文本用完时,请停止间隔.

You're queuing up 22 calls at once, all happening 3 seconds later. Just create your interval once, outputting new text on each call. Stop the interval when you've run out of text.

function thanks() {   
  $("#writer").text("");
  var txt = "Thanks for visiting !";
  var i = 0;

  var int = setInterval( function() 
  {
    ++i;
    if (i > txt.length)
    {
      clearInterval(int);
      return;
    }

    var type = txt.substring(0, i);
    $('#writer').text(type);
  }, 3000);
}

示例: http://codepen.io/paulroub/pen/AwLfx

这篇关于在内部以设置的间隔循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 23:05