JS中循环的时间

时间:2018-11-13 18:27:29

标签: javascript html for-loop settimeout

我用JS编写了这段代码:

function startFunction() {
p1 = document.getElementById('p1').innerHTML;
for (var i=1; i<=p1.length; i++) {
        alert(p1.slice(0, i));
    }
}

我用html中的onload事件调用该函数:

    <body onload="startFunction()">

这是具有 p1 id的段落:

    <p id="p1">Hi, I'm</p>

如何延迟for循环。我希望我的程序逐个字母地写 p1 文本。

5 个答案:

答案 0 :(得分:1)

var alertEachLetter =function(p1, i){
    setTimeout(function(){
        alert(p1.slice(0, i));
    },1000);
};

 function startFunction() {
 p1 = document.getElementById('p1').innerHTML;
 for (var i=1; i<=p1.length; i++) {
        alertEachLetter(p1, i);
    }
}

为什么创建此alertEachLetter函数。为此,您需要检查此链接

setTimeout in for-loop does not print consecutive values

答案 1 :(得分:1)

您不能也不应在循环内延迟任何操作,因为这是无响应页面的制作方式:浏览器在JavaScript代码返回之前不会对用户操作做出任何反应或执行任何可见的操作。

相反,您可以使用一些计时器,例如setInterval()

function startFunction() {
    var p1 = document.getElementById('p1');
    var txt = p1.innerHTML;
    var i=0;
    var timer = setInterval(function() {
        p1.innerHTML = txt.slice(0,i++);
        if(i>txt.length) {
            clearInterval(timer);
        }
    },500);
}

startFunction();
<p id="p1">Hi, I'm</p>

答案 2 :(得分:1)

您不需要循环,您需要interval。 JavaScript的interval功能将(大约)在请求的时间间隔内调用您的函数。因此,例如:

function startFunction() {
  var p1 = document.getElementById('p1').innerHTML
  var count = 1
  var finished = p1.length
  var iv = setInterval(function() {
    alert(p1.slice(0,count++))
    if (count > finished) {
      clearInterval(iv) // stops the interval from firing once we finish our task
    }
  }, 1000) // 1000 ms, or every second.
}

答案 3 :(得分:1)

这是一个使用setTimeout而不是setInterval的简单示例。除了不需要清除超时以外,没有太大区别,只要不满足条件就不要运行它。

// cache the elements
const p1 = document.getElementById('p1');
const out = document.getElementById('out');

// make the text content from p1 iterable and split it into
// the head (first element), and tail (everything else)
const [head, ...tail] = [...p1.textContent];

const loop = function loop(head, tail) {

  // update the output text content with the result of head
  out.textContent = head;

  // if there's anything left of the tail array
  if (tail.length) {

    // remove the first element of tail and
    // add it to head
    head += tail.shift();

    // call the function again with the new head and tail
    setTimeout(loop, 200, head, tail);
  }

// pass in the head and tail to the function
}(head, tail);
#p1 { display: none; }
<p id="p1">Content written letter by letter</p>
<p id="out"></p>

答案 4 :(得分:0)

以下是我认为可以帮助您实现自己想做的事情的一种方法。此方法使用setInterval(而不是循环)多次执行一个函数。请参阅注释以了解代码逻辑:

//Grab our DOM elements
var p1 = document.getElementById('p1').innerHTML;
var copy = document.getElementById('copy');

//Execute a function every 250 milliseconds
var intervalId = setInterval(onInterval, 250);

//nextLetter is a function that will return the character at a particular index in the string. The function will increase the index each time it is called. The function will return null once it exceeds the innerHTML length. c is a "private" variable that can't be modified elsewhere in the program.
var nextLetter = (function(i, limit) {
  var c = i;
  return function() {
    var idx = c++;
    if (idx > limit) {
      return null;
    }
    return p1.charAt(idx);
  };
})(0, p1.length);

//The function we will execute at each interval
function onInterval() {
  var letter = nextLetter();
  if (letter) {
    copy.innerHTML += letter;
  } else {
    console.log('End of content reached - removing interval');
    clearTimeout(intervalId);
  }
}
<p id="p1">Make sure to read the in-code comments</p>
<p id="copy"></p>