簡體   English   中英

不運行其他代碼行的延遲

[英]delay for not running other lines of code

在這段代碼中,我想當 .ch1 類的 div 將背景更改為 answer_box_small_orange.png 其他底部 js 行代碼不運行並且直到 3 秒才發送 ajax 請求,我使用

window.setTimeout(function () {}, 3000)

但它不能正常工作

這里首先我請求並獲取數據,沒關系

$.ajax({
    type:'post',
    url:'http://207.154.251.233:8039/app.php/question/get',
    data:JSON.stringify({apikey:'jwebdpqodp9fgkwjebfkdpqihdqlwkndqp'}),
    success:(function (response) {
        var x = response;
        $("#question").text(x.result.question);
        $(".op1").text(x.result.options["1"]);
    })
});

我在函數中插入了 ajax 代碼和其他一些代碼,因為我想每 60 秒運行一次

function myInterval () {
    $(".ch1").css('background-image','url(image/answer_box_small.png)');
    var clock;
    $(document).ready(function() {
        clock = new FlipClock($('.clock'), 60, {
            clockFace: 'Counter',
            autoStart: true,
            countdown: true,
            callbacks: {
                stop: function() {
                    $('#loading').fadeIn('5000');
                    $.ajax({
                        type:'post',
                        url:'http://79.175.166.98/',
                        data:JSON.stringify({apikey:'jwebdpqodp9fgkwjebfkdpqihdqlwkndqp'}),
                        success:(function (response) {
                            $('#loading').fadeOut('slow');
                            var x = response;
                            $("#question").text(x.result.question);
                            $(".op1").text(x.result.options["1"]);
                            var answer = x.result.answer;
                            if(answer == 1){
                                $(".ch1").css('background-image','url(image/answer_box_small_orange.png)');
                            }
                           window.setTimeout(function () {}, 3000);
                        })
                    });
                }
            }
        });
    });
}
myInterval();
window.setInterval(function(){
    myInterval();
}, 60000);

根據你告訴我的,我的解釋是你有一個setTimeout()函數和一個setInterval()函數。 setTimeout()在開始時運行並等待 3 秒。 然后每 6 秒調用一個ajax函數來創建新請求。 您的問題似乎是您的第一個setTimeout()在您創建第一個AJAX請求后重新運行,但您希望它停止。

取自W3

setTimeout 返回值:一個數字,表示設置的定時器的 ID 值。 將此值與 clearTimeout() 方法一起使用以取消計時器。

知道了這一點,我們基本上可以取消setTimout()函數。 在您的情況下,第一個setTimeout()

考慮到這一點,

var firstIntervalID = setTimeout(function() {
    $.ajax() {
    // First AJAX ran after three seconds.
    }
}, 3000);

clearTimeout(firstIntervalID);

// Your code resumes to set an interval every 60 seconds without having to worry about the three seconds set before
myInterval();
var secondIntervalID = setInterval(function(){
    myInterval();
}, 60000);

本質上,當您不再需要setTimeout()時,您可以取消它。 您的申請可能與我寫的有所不同,但主要思想是相同的。 使用在setTimeout()clearTimeout()上返回的ID取消/清除setTimeout() clearTimeout()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM