【问题标题】:Why is my synchronous code using setTimeout behaving asynchronous in JavaScript?为什么我的使用 setTimeout 的同步代码在 JavaScript 中表现异步?
【发布时间】:2014-03-28 23:06:31
【问题描述】:

我正在尝试在测试中循环 10 倍(等待条件为真),但不知何故它不起作用。

这是我所拥有的:

// my counter
$.testHelper.countDown = function(test, iteration) {
    var ticker = iteration || 0;
    if (ticker > 10) {
      return false;
     }
    window.setTimeout(function() {
        if (test === true) {
            console.log("SENDING");
            return true;
        }
        ticker += 1;
        $.testHelper.countDown(test, ticker);
     }, 1000);
    };

    // my test     
    $.testHelper.testForElement = function(element) {
        var result;   
        console.log($i.find(element).length > 0); // true
        result = $.testHelper.countDown(
             $i.find(element).length > 0
        );
        console.log(result);  // undefined
        return result;
     };

我的问题是,虽然在我调用倒计时之前我的条件等于true,但countDown 的答案是undefined。所以我的日志是这样进来的:

// true - before firing my countDown method
// undefined - should not log
// SENDING - response from countDown (= true)

问题
从显示的代码来看,为什么我的undefinedcountDown通过并返回true之前被记录是有原因的吗?

谢谢!

【问题讨论】:

    标签: javascript jquery jquery-mobile timeout qunit


    【解决方案1】:

    Erm,因为setTimeout总是 异步的?这就是重点。

    这里有一个适合你的可能性:

    function when(condition,then) {
        // condition must be a callback that returns `true` when the condition is met
        if( condition()) then();
        else setTimeout(function() {when(condition,then);},1000);
    }
    

    这将每秒轮询一次,直到满足条件,然后执行then 回调中给出的任何操作。

    【讨论】:

    • 我不明白你在做什么,所以......不,对不起!
    • 我正在等待一个元素“出现”(= 被生成),所以我想循环 10 倍并检查它是否存在。
    • 你可能需要使用回调
    • @frequent well setTimeout() 立即返回。您传递给它的函数将在计时器到期时被调用。因此,如果您希望它在一段时间后发生,则需要将代码放入计时器处理程序中。
    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多