javascript - 暂停脚本直到函数完成 - jquery

标签 javascript jquery

我有一个简单的计数函数,将数字递增到输入字段中。这正是我希望的工作方式。唯一的问题是,我有一个很长的具有多个函数的 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/

相关文章:

javascript - CSS 颜色样式取决于返回的 Ajax 响应

jquery - HTML 和 CSS 对齐

javascript - 如何使用 jquery 获取 <li> 标签内的字符串

javascript - 创建一个 jQuery 插件 : best practices regarding functions' visibility?

javascript - 在开关盒中放置开关盒是不好的做法吗?

jquery - 如何获取 Ajax.BeginForm 和 OnSuccess 之间的事件?

javascript - 带标签的旋转木马 : adjust active tab when carousel slides to next or previous slide

javascript - 如何为传入列表项制作工具提示

Jquery 对话框在回发后关闭

javascript - dojo xhrPost 进度(回调)事件监听器?