我有一个简单的计数函数,将数字递增到输入字段中。这正是我希望的工作方式。唯一的问题是,我有一个很长的具有多个函数的 JS 脚本,我只希望该脚本在 count()
函数完成时继续运行。
JSFIDDLE http://jsfiddle.net/vyN6V/243/
var number = 1500;
var aValue = 300;
function count(Item) {
var current = aValue;
Item.val(aValue += 1);
if (current < number) {
setTimeout(function () {
count(Item)
}, 0.1);
}
}
count($(".input"));
// the rest of the script should only run when the above function has completed
$('span').text('code here should only run when function count is complete');
最佳答案
您需要的是回调。我确信您已经使用过回调,例如在 jQuery 中。
以下是将其添加到代码中的方法:
function count(Item, Callback) { // new argument
var current = aValue;
Item.val(aValue += 1);
if (current < number) {
setTimeout(function () {
count(Item, Callback) // pass it in recursive calls
}, 0.1);
} else {
Callback(); // call it at the end of the loop
}
}
count($(".input"), function() { // write the callback code here
// this will be executed after the counts
});
关于javascript - 暂停脚本直到函数完成 - jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21995057/