0

I'm having a problem with my function. It's a function made to display every word of an array one bye one, for one second, when you press a button, but for some reason it tells me I'm calling too much, despite making sure to put a loop to check if it can be called. Here it is

var liste = ["one", "two", "three", "four", "five"]; //Changer la liste par la liste de syllabes qu'on veut travailler. Je ne sais pas encore comment l'importer d'un fichier txt
    var text = document.getElementById("myText");
    var btn = document.getElementById("myBtn");
    btn.addEventListener("click", showsyll(liste));

    function showsyll(arr) {
        var i=0;
            if (i < arr.length) {
                text.innerHTML= arr[i++];
                setTimeout(showsyll(arr), 1000);
            }
            else {
                return
            }
        }

The html part is super simple, just a button and a text id

<p id="myText"></p>
<button type="button" id="myBtn">Press to show syllables</button>
Kirout
  • 5
  • 2
  • Does this answer your question? [How can I pass a parameter to a setTimeout() callback?](https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) – Alon Eitan Feb 06 '21 at 15:54
  • `setTimeout(showsyll(arr), 1000);` - That's your problem, you think that it will call the function using the timeout but it actually calls the function immediately – Alon Eitan Feb 06 '21 at 15:55
  • I've tried changing according to that post, replacing my `setTimeout(showsyll(arr), 1000);` by `setTimeout(function() { showsyll(arr); }, 1000)` but now it just... doesnt do anything? I'm frairly new to javascript.. – Kirout Feb 06 '21 at 16:13

1 Answers1

0

Firstly your i always being zero because it define in your callback function and i called your functions in arrow functions now its working:

    var liste = ["one", "two", "three", "four", "five"];
        var text = document.getElementById("myText");
        var btn = document.getElementById("myBtn");
    
        var i;
        btn.addEventListener("click", ()=>{
            i=0;
            showsyll(liste);
        });
        function showsyll(arr) {
                if (i < arr.length) {
                    text.innerHTML= arr[i];
                    i+=1;
                    setTimeout(()=>{
                        showsyll(arr);
                    }, 1000);
                }
                else {
                    return
                }
            }
    <p id="myText"></p>
    <button type="button" id="myBtn">Press to show syllables</button>
    
    
    


            
            
 
  • This works perfectly! Mind explaining what the `()=>` mean? I havent seen those yet – Kirout Feb 06 '21 at 16:37
  • its function define method , ()=> its came with ecmascript6 and being your functions short , you don't need write function(){} , there are some differences with function(){} but generally same. – Reşit Abdullah Yavuzkol Feb 06 '21 at 16:46