Solution 1 :

Your function runs correctly, the problem is in the function code itself, not in setInterval.

Doing this:

string = string.replace(/_/, char);

You’re always trying to replace the _ character. From the second time your function is called, that character will not be present anymore since it got replaced by the first call.

If you want the last character to keep changing, you have multiple options:

string = string.substrstring.replace(/.$/, char);
// or
string = string.substrstring.slice(0, -1) + char;
// or even just
buttons[i].textContent = 'help' + char;

The regexp .$ matches any character that is at the last position in the string ($ matches the end of the string), but it’s probably the slowest option.


Working snippet:

const buttons = document.getElementsByTagName('button');

setInterval(charChange, 1000);

function charChange(){
    let string;
    let chars = ['#', '!', '@', '$', '%', '&', '+', '?'];
    for(i = 0; i < buttons.length; i++){
        let char = chars[Math.floor(Math.random() * 7)];
        buttons[i].textContent = 'help' + char;
    }
}
<button id = 'title'>help_</button>

Problem :

setInterval only executes once. I have also tried using setTimeout and placing it inside the function to cause a loop, but that gives the same result. I am using brackets and it’s live preview if that makes a difference.

const buttons = document.getElementsByTagName('button');

setInterval(charChange, 1000);

function charChange(){
    let string;
    let chars = ['#', '!', '@', '$', '%', '&', '+', '?'];
    for(i = 0; i < buttons.length; i++){
        string = buttons[i].textContent;
        let char = chars[Math.floor(Math.random() * 7)];
        string = string.replace(/_/, char);
        buttons[i].textContent = string;
    }
}
<button id = 'title'>help_</button>

Comments

Comment posted by StackSlave

No, it executes every second. Your function just keeps doing the same thing. What’s the point of this on button

Comment posted by Marco Bonelli

@Craftingexpert1 this is

Comment posted by Kavelin

Sorry about that, i didn’t see that.

By