3

データベース エントリが存在するかどうかを確認する関数を実行しています。

ページの読み込み時に、要素が存在するかどうかを確認し、存在する場合はsetInterval関数を実行します。そのようです:

if ( $('#encoding').length ) {

    console.log("auto_update start");
    var update = setInterval(auto_update, 12000);
}

次に、私のauto_update機能でこれが起こります

function auto_update() {

    console.log("auto_update running");

    $.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {
            action: "dhf_ajax_router",
            perform: "dhf_check_status", // the function we want to call
            post_id: $('#post_id').val(),
            nonce: $('#dhf-video-meta-nonce').val()
        },
        success: function(response) {

            if ( response === "continue" ) {

                console.log("still encoding");

            } else {

                clearInterval(update);
                console.log("complete " + response);
            }
        }
    });
}

問題は$('#encoding')、開始時にページに存在せず、ユーザーが次の範囲内で手動で起動した場合です。

$(document).on("click", ".run_encode", function(){

        // doing the necessary stuff here.
        if ( response === "sent" ) {

                // more stuff
                var update = setInterval(auto_update, 12000);
        } 

}); // end .run_encode

その後、clearInterval(update)は機能せず、無限ループに陥ります。

理由がわかりません。どちらの場合も名前付きの間隔updateが設定されているのに、2 番目の状況ではクリアが機能しないのはなぜですか?

4

2 に答える 2

4

update関数内で変数を宣言します。他の関数はその値にアクセスできません。

jfriend00は、それを解決する方法について広範な回答をしました。私は別のルートを取ります:を使用しますsetTimeout。AJAX呼び出しは一定の時間はかからず、毎回変化するため、これはとにかくお勧めします。ネットワークの問題が原因で12秒以上かかると想像してみてください。

于 2012-08-10T07:20:48.000 に答える
2

update共有変数が両方のスコープで利用可能であることを確認する必要があります。これは、共通の親スコープ内にある必要があるかupdate、スコープ外に出ないように変数をグローバル変数にする必要があることを意味します。

ほとんどの場合、終了する関数内で is を宣言しupdateており、その関数が終了すると、update変数はスコープ外になり、破棄されます。

変数の初期設定をグローバルスコープに入れることができます(したがって、次のように呼び出しても引き続き使用できますclearInterval()

$(document).on("click", ".run_encode", function(){

    // doing the necessary stuff here.
    if ( response === "sent" ) {

            // more stuff
            window.update = setInterval(auto_update, 12000);
    } 

}); // end .run_encode

または、変数をグローバルとして宣言することもできます。update最初にこれをグローバル レベル (関数の外) に置き、次にこのコードでグローバル変数を変更します。

var update;

$(document).on("click", ".run_encode", function(){

        // doing the necessary stuff here.
        if ( response === "sent" ) {

                // more stuff
                update = setInterval(auto_update, 12000);
        } 

}); // end .run_encode
于 2012-08-10T07:35:42.900 に答える