Problem with typewriter prototype

I wonder if anyone could help find a solution to a problem I’m having with a typewriter effect prototype?

The code I’m using to achieve the effect is:


TextField.prototype.typeWriter = function(type_str:String, type_speed:Number) {
	var type_field:TextField = this;
	type_field.text = "";
	var type_counter:Number = 0;
	var type_interval:Number = setInterval(function () {
		type_field.text = type_field.text+type_str.charAt(type_counter)
		type_counter++;
		if (type_counter == type_str.length) {
			clearInterval(type_interval);
		}
	}, type_speed)
}

Which is activated by


myTextField.typeWriter(myText, typeSpeed);

It all works fine, but my problem is that if I use it to display a new string in the same text field before the previous string has finished ‘typing’, the previous string and new string are typed at the same time, resulting in a spliced textfield of gobbledegook - characters from each string are displayed alternately, for example:

If I feed “goodbye” into the function before “hello” has finished, I get “hgeololdobye”.

I presume that what I need to do is clear the previous string before using a new string, which I’ve tried to do by using


myTextField.text = "";

before calling the typewriter function, but that doesn’t work. Can anyone tell me what I need to do? Something within the prototype? It’s reached tearing hair out stage…

Thanks

What you actually need to do is to check to see whether type_interval exists. If it does, then you should clear the interval like so:

TextField.prototype.typeWriter = function(type_str:String, type_speed:Number) {
	if (type_interval != null) {
		trace("clearing previous Interval");
		clearInterval(type_interval);
	}
	var type_field:TextField = this;
	var type_counter:Number = 0;
	type_interval = setInterval(function () {
		type_field.text = type_field.text + type_str.charAt(type_counter);
		type_counter++;
		if (type_counter == type_str.length) {
			clearInterval(type_interval);
		}
	}, type_speed);
};
myTextField.typeWriter("hello", 200);
myTextField.typeWriter("goodbye", 200);
myTextField.typeWriter("problem solved", 200);

Forgot to mention…the other change was to **not **use the var statement when declaring your interval. Using var causes the interval to be declared locally so that it only exists inside the setInterval function; therefore any attempt to check whether it exists (because you’re already running an instance of the typeWriter function), or to delete it outside of the setInterval function, will fail.