gpt4 book ai didi

JavaScript:如何在执行条件的特定持续时间后清除间隔

转载 作者:行者123 更新时间:2023-11-30 23:54:28 25 4
gpt4 key购买 nike

我需要运行下面的代码,并在 10 秒后停止 SetInteraval 函数,但同时确保完整的字已被执行。

我编写的代码:

var word = "I love JS More than any Programming Language in the world!";
var counter = 0;

var autoTyping = setInterval(function() {
var h3 = document.getElementById("myh3");
h3.innerText = word.substring(0, counter);
counter++;

if (counter > word.length) {
counter = 0;

}

}, 100);


setTimeout(function() {
clearInterval(autoTyping);
}, 5000);

所以我需要在 5 秒后停止此代码,并且发生了这种情况,但可以在不确保完整单词“Variable word”已完全写入 DOM 的情况下停止。

最佳答案

我假设您想要将每个字母的 word 变量打印到 h3 元素,并在 5 秒后停止,并且变量已完全输入。

这是我使用递归方法的解决方案:

[更新]

  • 添加了带有超时停止器的输入循环
<小时/>

// word to type
var _word = "I love JS More than any Programming Language in the world!"

// target element's id
var _target = 'myh3'

// time to fully-typed the word
var _time = 5000 // ms

// speed is depend on _time and _word's length
var _speed = _time/_word.length

// your auto-typing stopper
var _timeout = 10000 // ms

// auto-typing function
function autoType (word, target, speed, timeout) {
var element = document.getElementById(target)
var counter = 0
var stopped = false

function typing(){
if(counter < word.length){
element.innerHTML += word[counter]
counter++

setTimeout(function(){
// recursive call
typing()
}, speed)
}else{
// check if you want it to stop
if(stopped === false){
// ok. you don't want it to stop now. reset counter
counter = 0

// reset the element if you want it too
element.innerHTML = ''

// start it again
typing()
}else{
// console.log('auto-typing is done')
}
}
}

// timeout is required. you dont want a infinite loop, right?
if(timeout){
typing()

setTimeout(function(){
stopped = true
}, timeout)
}
}

// execute it
autoType(_word, _target, _speed, _timeout)
body {background: white}
<h3 id="myh3"></h3>

关于JavaScript:如何在执行条件的特定持续时间后清除间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61155401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com