Reputation: 1
I'm no javascripter. I know enough to copy, paste, and tinker. But I can't make enough sense of this script to add a setTimeout, going off of the W3 example.
Here's the script I'm using for a text type animation. I'd like to delay the function by a few ms. How can I go about doing that?
<script type="text/javascript">
var TxtType = function(el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 8) || 200;
this.txt = '';
this.tick();
this.isDeleting = false;
};
TxtType.prototype.tick = function() {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 2.5);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';
var that = this;
var delta = 122 - Math.random() * 110;
if (this.isDeleting) { delta /= 2; }
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 900;
}
setTimeout(function() {
that.tick();
}, delta);
};
window.onload = function() {
var elements = document.getElementsByClassName('typewrite');
for (var i=0; i<elements.length; i++) {
var toRotate = elements[i].getAttribute('data-type');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtType(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".typewrite > .wrap { border-right: 0.08em solid #fff}";
document.body.appendChild(css);
};
Upvotes: 0
Views: 98
Reputation: 10998
To delay a function with setTimeout
, you need to do something like this:
var myFunction = function() {
// awesome stuff
};
setTimeout(myFunction, 1000);
This will run myFunction
after 1000ms have elapsed.
You can also define the function you want to delay anonymously as the first argument to setTimeout
like so:
setTimeout(function() {
// awesome stuff
}, 1000);
These two versions of using setTimeout
are identicle.
Upvotes: 1