I have a jQuery function that uses setInterval() to slowly type out a phrase–like with the phrase “string one”, each character would be printed to the screen after a set number of milliseconds.
The problem is that in my code, I have two calls to the function one right after the other, and they’re overlapping because it appears that setInterval() doesn’t stop the normal flow of code. It’s hard to explain, here’s my jsFiddle that shows what happens.
Here’s my function:
function type(text) {
if(intv == null) {
var textArray = text.split("");
var length = textArray.length - 1;
var i = 0;
$("#div").append('<p class="text' + n + '"></p>' + "\n"); // creates a paragraph to print every character to (n is a global var)
intv = setInterval(function() {
if(i <= length) {
var a = textArray[i];
$('#div .text' + n).text($('#div .text' + n).text() + a); // appends the character to the paragraph created above
i++;
}
else {
alert("stopping interval..."); // just lets me know when the interval is stopping
clearInterval(intv);
intv = null;
n++;
}
}, 60);
}
else {
alert("the interval is not null"); // lets me know if the previous setInterval has stopped firing
}
}
And here’s how I’m calling it:
type("string one");
type("string two");
The problem is that both “string one” and “string two” end up firing at the same time, and either start infinitely looping or only the first one works.
I really don’t know if there’s a way to fix this, and my searches have yielded nothing. I don’t know if this is a common problem or not. Is there a way that I can keep the second string from firing until the first one is done?
Thanks ahead of time.
Have a look here: http://jsfiddle.net/ymxu5/12/
First, set up a function queue that will keep track of where we are:
You’ll then need to adapt your methods to use
queue.next();. I’ve set up theQueueobject to call each function, changing the context ofthisto theQueueobject, which is whyvar queue = this;is used.You’ll want to have a
Queueobject accessible throughout your scope. I made it global here:I also took the liberty of making the
addmethod chainable, so you can use it like above.
here’s an example of using a few methods to create a console-like interface:
http://jsfiddle.net/ymxu5/15/