+ 1
What the hell is going on here
11 odpowiedzi
+ 2
+ 4
First, you must make distinction between setInterval() and setTimeout()... regarding which one you prefer to use, you need to do slightly different ^^
Second, you must know that both timing (delay) functions return an identifier, useful to stop/disabled them...
Actually the last fix of @Vladi Petrov still have a defect: if you click the button more than once before end of text display, the speed will be increased, because you start more than once 'setInterval' running at same time ^^
Next, you don't need to enclose the 'secondary' function ('append()') in the 'primary' one ('tekst()' called by the onclick event, which purpose is to start the intervaled loop call), and you have to test if the setInterval() was already started (ie: by saving the state in a flag variable on first call) or disabled either the button or the button onclick event...
Finally, its a better practice to relase (stop/disabled) the setInterval when full text is outputed, because it will continue to consume ressources.
var i=0;
var run=false;
var timer_id = null;
function tekst(){
if (run == true) return;
document.getElementById("tekst").innerHTML=''; // clear content at start (on click)
timer_id = setInterval(append, 60);
run = true;
}
function append(){
var br = "<br>";
var story = "Blaas eerst de ballon op.% Maak daarna met een mesje of een schaar ern gat in het tuitje van de ballon.% Steek je middelvinger door het gat en sla tegen de ballon.% Gefeliciteerd, je hebt nu je arm verlamd!";
if(story[i] == "%"){
tekst.innerHTML += br;
i++;}
if(i < story.length){
document.getElementById("tekst").innerHTML+=story[i];
i++;}
else {
run = false;
i = 0;
clearInterval(timer_id);
}
}
There are many improvments that you could add, but I don't want to confuse you with more stuff/information ^^
+ 2
I want it to work that if you click the button, the full text will appear, and not only "BBBBBBBBBBBBBBBBBBBBBBB"
+ 2
https://code.sololearn.com/W10MMlIozD8C/?ref=app
Now I think everything is ok :D
+ 1
How do you want to work?
0
thanks, now I see how important the smallest details are!
0
now i have it working correctly, but it already starts writing on its own, and if i do it so you have t click on the butten (put function before var story) it will write this : B-l-aa-s eer-st de ba- etc, can anyone help me with this?
0
btw there is a riddle behind it: (if thats important)
1. i = 1 (0+1)
2. i = 2 (1*2)/(1^2)
3. i = 4 (2*2)/(2^2)
4. i = 8 (4*2)/(3^2)
5. i = 16 (8*2)/(4^2)
6. i = 32 (16*2)/(5^2)
0
that, unfortunatly still lets the text type before the buttonclick
0
thanks man