Reputation: 468
My question is this: I have two jquery functions, and they both fill out fields in a form. Currently they run at the same time, but how can I get it run the second script only after the first is finished?
var string = '[email protected]',
letters = string.split(''),
total = letters.length,
index = 0,
timer = setInterval(function () {
if (index < total) {
$('input[name="email"]').val(function () {
return $(this).val() + letters[(index++)];
});
} else {
clearInterval(timer);
}
}, 100);
var stringtwo = 'Jason',
ttert = stringtwo.split(''),
totaltwo = ttert.length,
countt = 0,
timer = setInterval(function () {
if (countt < totaltwo) {
$('input[name="first"]').val(function () {
return $(this).val() + ttert[(countt++)];
});
} else {
clearInterval(timer);
}
}, 100);
Upvotes: 0
Views: 47
Reputation: 1487
After you clear the first you could start the second.
var string = '[email protected]',
letters = string.split(''),
total = letters.length,
index = 0;
var timer = setInterval(function () {
if (index < total) {
$('input[name="email"]').val(function () {
return $(this).val() + letters[(index++)];
});
} else {
clearInterval(timer);
var stringtwo = 'Jason',
ttert = stringtwo.split(''),
totaltwo = ttert.length,
countt = 0;
timer = setInterval(function () {
if (countt < totaltwo) {
$('input[name="first"]').val(function () {
return $(this).val() + ttert[(countt++)];
});
} else {
clearInterval(timer);
}
}, 100);
}
}, 100);
Or something similar.
Upvotes: 1
Reputation: 34107
Something like this: reference Wait till a Function with animations is finished until running another Function
API : http://api.jquery.com/deferred.done/
This might fit your needs :)
Code
var FunctionOne = function () {
var string = '[email protected]',
letters = string.split(''),
total = letters.length,
index = 0,
timer = setInterval(function () {
if (index < total) {
$('input[name="email"]').val(function () {
return $(this).val() + letters[(index++)];
});
} else {
clearInterval(timer);
}
}, 100);
};
// define FunctionTwo as needed
var FunctionTwo = function () {
var stringtwo = 'Jason',
ttert = stringtwo.split(''),
totaltwo = ttert.length,
countt = 0,
timer = setInterval(function () {
if (countt < totaltwo) {
$('input[name="first"]').val(function () {
return $(this).val() + ttert[(countt++)];
});
} else {
clearInterval(timer);
}
}, 100);
};
// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);
Upvotes: 0