Following code snippet helped me to learn setTimeout more easily specially when you use setTimeout with for loop. One thing have to be remember when you call setTimeout inside for loop time parameter will be (i * time). and i will be (1 , 2, 3, 4, 5 .. this sequence)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this is the basic of setTimeout function</title>
</head>
<body>
<h2 id="subtitle">Hello my name is shibu deb polo...</h2>
<script type="text/javascript" charset="utf-8">
function backlash(id) {
var subtitle = document.getElementById(id);
var text = subtitle.innerHTML;
var time = 50;
for (let i = text.length; i >= 0; i--) {
setTimeout(function () {
subtitle.innerHTML = subtitle.innerHTML.substring(0, i);
}, time + time * (text.length - i))
}
setTimeout(function () {
textAdd('subtitle', text);
}, 2000);
}
function textAdd (id, text) {
var subtitle = document.getElementById(id);
console.log(text ,'text')
for (let i = 0 ; i < text.length ; i++) {
setTimeout(function () {
subtitle.innerHTML += text[i]
console.log(text[i]);
}, 100 * i)
}
setTimeout(function () {
backlash('subtitle');
}, 4000)
}
backlash('subtitle');
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>this is the basic of setTimeout function</title>
</head>
<body>
<h2 id="subtitle">Hello my name is shibu deb polo...</h2>
<script type="text/javascript" charset="utf-8">
function backlash(id) {
var subtitle = document.getElementById(id);
var text = subtitle.innerHTML;
var time = 50;
for (let i = text.length; i >= 0; i--) {
setTimeout(function () {
subtitle.innerHTML = subtitle.innerHTML.substring(0, i);
}, time + time * (text.length - i))
}
setTimeout(function () {
textAdd('subtitle', text);
}, 2000);
}
function textAdd (id, text) {
var subtitle = document.getElementById(id);
console.log(text ,'text')
for (let i = 0 ; i < text.length ; i++) {
setTimeout(function () {
subtitle.innerHTML += text[i]
console.log(text[i]);
}, 100 * i)
}
setTimeout(function () {
backlash('subtitle');
}, 4000)
}
backlash('subtitle');
</script>
</body>
</html>
Hello my name is shibu deb polo...