你好我刚接触javascript,我试图找出如何在规定的时间后追加一个字符串。
After 3 secs append string (How)
After 3 secs append string (are)
After 3 secs append string (you)
After 3 secs append string (?)
谢谢:D
答案 0 :(得分:3)
使用setTimeout
。
var text = 'How are you ?'.split(' '),
delay = 3000;
function generateCallback(text) {
return function () {
alert(text);
};
}
for (var i=0; i<text.length; i++) {
setTimeout(generateCallback(text[i]), delay*(i+1));
}
答案 1 :(得分:1)
<html>
<head></head>
<body>
<span id="mySpan"></span>
</body>
<script>
setTimeout('document.getElementById("mySpan").innerHTML += "How ";', 3000);
setTimeout('document.getElementById("mySpan").innerHTML += "are ";', 6000);
setTimeout('document.getElementById("mySpan").innerHTML += "you";', 9000);
setTimeout('document.getElementById("mySpan").innerHTML += "?";', 12000);
</script>
</html>
答案 2 :(得分:0)
作为当前答案的修改,可以使用单个setInterval
电话,在显示所有字词时取消:
// s is string to display
// interval is the time in milliseconds between adding words
// id is the id or reference to a DOM element to display s in
function staggerDisplay(s, interval, id) {
var el = typeof id == 'string'? document.getElementById(id) : id;
var sBits = s.split(' ');
var numWords = sBits.length;
var i = 0;
var intervalRef = setInterval(
function () {
if (i < numWords) {
el.innerHTML += ' ' + sBits[i++];
} else {
clearInterval(intervalRef);
}
}, interval);
}