Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 697
twondai Avatar asked Sep 02 '25 02:09

twondai


1 Answers

The first time you run it, you have one interval running every 100ms.

The second time you run it, you have two intervals, each running every 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.


Either:

  • Call clearInterval(...) when you've finished
  • Pass the global variables as arguments to talky so they aren't shared between the multiple intervals
  • Just update the variables instead of calling talky again
like image 73
Quentin Avatar answered Sep 04 '25 14:09

Quentin