2017-10-16 171 views
-2

在這段代碼我想當div與.ch1類改變背景answer_box_small_orange.png其他底部js行代碼不運行,沒有ajax請求發送,直到3秒,我用延遲不運行其他代碼行

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); 
+1

'setTimeout'不會阻止腳本,它只是安排稍後運行的函數。 – Barmar

+0

@Barmar我怎麼能阻止腳本例如3 seconds.im困惑。我GOOGLE了它,沒有什麼有用的發現 – sepehr

+0

你沒有找到任何東西,因爲它幾乎總是錯誤的JavaScript阻止頁面。 Javascript沒有這樣做。 – Barmar

回答

0

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

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()IDsetTimeout()clearTimeout()返回。