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>