![](/img/trans.png)
[英]time delay between 2 lines of code in javascript, not settimeout
[英]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.