Can someone assist with a JavaScript issue I am facing? I tried using a function in a variable for a typing effect and passed the variable into setInterval method, but it didn't work. However, when I placed the same function directly inside setInterval
, it worked perfectly. Any idea why this happened?
var button = document.getElementById('mybutton');
var mytext="thequickredfoxjumpsoverthelazybrowndog";
//var i=0;
//var typewriter = null;
// first code function in var
var x = function() {
document.getElementById('type')
.textContent += mytext[i];
i = i + 1;
if (i > 20) {
clearInterval(typewriter);
}
};
mybutton.onclick = function() {
'user strict';
typewriter = setInterval(x, 10);
};
<input type="button" id="mybutton">
<div id="type"></div>
var button = document.getElementById('mybutton');
var mytext="thequickredfoxjumpsoverthelazybrowndog";
var i=0;
var typewriter = null;
// second code function directly in setInterval
mybutton.onclick = function() {
'user strict';
var typewriter = setInterval(function() {
document.getElementById('type')
.textContent += mytext[i];
i = i + 1;
if (i > 20) {
clearInterval(typewriter);
}
}, 10);
};
<input type="button" id="mybutton">
<div id="type"></div>