2017-10-16 106 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()返回。