简体   繁体   English

Javascript setInterval每次运行时都会变短

[英]Javascript setInterval getting shorter every time it runs

So i've made a function that prints out text letter by letter, shown below.(i know my naming scheme isn't great pls don't make fun. also keep in mind i'm still fairly new to coding so my code might seem a bit odd/inefficient.) 所以我已经制作了一个逐字打印文本的功能,如下所示。(我知道我的命名方案不是很好,请不要取笑。还要记住我还是很新编码所以我的代码可能看起来有点奇怪/低效。)

var text = document.getElementById("gametext")
var dialog =  "the entire text you want to print out"
var talk = "The whole text gets added here, letter by letter"
var charinc = 0

function talky() {
   setInterval(function(){
   if(charinc < dialog.length){
   talk = dialog.charAt(charinc++);
   text.innerHTML += talk;  
   }
   }, 100);
   charinc = 0
}

and i call this function several times throughout my code, setting dialog to whatever it is i want to print, and then calling the function. 我在整个代码中多次调用此函数,将对话框设置为我要打印的任何内容,然后调用该函数。 And it all works fine at first, but every time i run it, it seems that the letters get printed out faster and faster. 这一切都很好,但每次我运行它,似乎字母打印得越来越快。 i'm not really sure what's going on, or how to fix it. 我不确定发生了什么,或者如何解决它。 i've done a few searches on google but nothing useful came up. 我在谷歌上做了一些搜索,但没有任何有用的信息。

The first time you run it, you have one interval running every 100ms. 第一次运行它时,每100ms运行一个间隔。

The second time you run it, you have two intervals, each running every 100ms. 第二次运行它时,你有两个间隔,每个间隔每100ms运行一次。

And so on. 等等。

Since they share the same variables, you just cause each one to increase the speed of the output by one write every 100ms. 由于它们共享相同的变量,因此您只需使每个变量以每100ms一次写入的速度提高输出速度。


Either: 或者:

  • Call clearInterval(...) when you've finished 完成后调用clearInterval(...)
  • Pass the global variables as arguments to talky so they aren't shared between the multiple intervals 将全局变量作为参数传递给talky这样它们就不会在多个区间之间共享
  • Just update the variables instead of calling talky again 只需更新变量,而不是再次调用talky

setInterval will let the function defined by it run every 100ms in your case. setInterval将让它定义的函数在你的情况下每100ms运行一次。 If you call this function several times like you say, there will be several intervals running parallel to eachother, which is probably not what you want. 如果你像你说的那样多次调用这个函数,会有几个间隔并行运行,这可能不是你想要的。

You can clear an existing interval by using clearInterval with the id that setInterval returns. 您可以使用clearInterval以及setInterval返回的id清除现有间隔。

eg 例如

var intervalId = setInterval(function() { console.log('hello, world!') }, 100); clearInterval(intervalId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM