0

I need to randomly change characters of a text and after some delay fix them.

There is my code:

<h1 id="text" style="margin-top:100px;">SOME TEXT</h1>

<script>
    var text = document.getElementById("text").innerHTML.split("");
    var myArr = text;

    for (i = 0; i < myArr.length; ++i) {

        var handle = setInterval(function () { xyz(i) }, 100);

        setTimeout(function (handle) {
            myArr[i] = text[i];
            clearInterval(handle);
        }, (i) * 1000);
    }

    function xyz(index) {
        myArr[index] = String.fromCharCode(Math.random() * 26 + 65);
        document.getElementById("text").innerHTML = myArr;
    }
</script>

It seems i have no a good understanding of how setInterval work! :(

EDIT:

With my code only text[text.length+1] character has change that mean passed parameter to xyx() function is last value of loop counter variable (after loop over). Now my question is how trigger setInterval() function with i = 0 ,1 ... , text.length.

Can someone guide me?

A.F.N
  • 199
  • 2
  • 15
  • And what problem are you currently experiencing? – Evan Knowles Jul 05 '17 at 10:35
  • problem is xyz(i) works on text[text.length+1] character always. i mean setIntervals triggers with i = text.length+1. i dont know how pass variable "i" to setInterval function. – A.F.N Jul 05 '17 at 11:55

2 Answers2

0

basicly setInterval execute a function with a iteration in time. and setInterval gives you a promise to cancel it any time you want.

var myPromise = setInterval(function(){
  //some code here
},delayMiliseconds);

to cancel this code

clearInterval(myPromise);
0

Related to this question problem was wrong way to passing arguments to setInterval().the callback function i passed to setInterval() maintains a reference to "i" rather than the snapshot value of "i" as it existed during each particular iteration...

<h1 id="text" style="margin-top:100px;">SOME TEXT</h1>

<script>
    var text = document.getElementById("text").innerHTML.split("");
    var myArr = document.getElementById("text").innerHTML.split("");
    for (i = 0; i < text.length; i++) {
        var handle = setInterval(function (k) { xyz(k) }, 100,i);

        setTimeout(function (handle, i) {
            console.log(i);
            console.log(text[i]);
            myArr[i] = text[i];
            clearInterval(handle);
        }, (i) * 1000,handle,i);
    }
    function xyz(index) {
        myArr[index] = String.fromCharCode(Math.random() * 26 + 65);
        document.getElementById("text").innerHTML = myArr.toString();       
    }
</script>
A.F.N
  • 199
  • 2
  • 15