[英]set and clear interval by ajax
I simply want to clear previous interval and set a new one when an ajax call is made.我只是想在调用 ajax 时清除先前的间隔并设置一个新的间隔。
The current code is:当前代码是:
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: {
'title': title
},
dataType: 'json',
success: function (data) {
var interval = null;
if(data.count_down){
var _second = 1000;
var _minute = _second * 60;
var timer;
var end = data.count_down
mins = Math.floor(end / 60);
secs = end % 60;
var interval = setInterval(count,1000)
function count(){
console.log(parseInt(secs))
secs -= 1
}}
else{
var stop = function(){
clearInterval(interval);}
}
}
})
})
I tryed many recommended variations to be able to clear the interval from outside of the function.我尝试了许多推荐的变体,以便能够从 function 外部清除间隔。 Such as;
如;
setting the "interval" variable to null or to false,将“间隔”变量设置为 null 或 false,
window.setInterval, window.setInterval,
writing the count function inside of setInterval,在 setInterval 中写入计数 function,
writing the count function as a separate function outside of the ajax function,将计数 function 作为单独的 function 在 ajax ZC1C425268E683894D1C47 之外写入
But neither of the variations cleared the interval.但是这两种变化都没有清除间隔。
Later on I'll also need to clear the interval on keydown.稍后我还需要清除 keydown 的间隔。
From your code, I will do like below (PS didn't test):从您的代码中,我将执行以下操作(PS 未测试):
var interval = null,
secs = 0;
function count() {
console.log(secs);
secs -= 1;
}
function deal_data(data) {
if(interval == null && data.count_down){
var end = data.count_down
secs = end % 60;
interval = setInterval(count, 1000);
else if (interval != null) {
clearInterval(interval);
}
}
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: { 'title': title },
dataType: 'json',
success: function (data) {
deal_data(data);
}
})
})
After several changes to MarshalSHI's answer the code ended up like this:在对 MarshalSHI 的答案进行了几次更改后,代码最终如下:
$("#title-form").change(function () {
var title = $(this).val().trim();
$.ajax({
url: '/ajax/timing_check/',
type: "get",
data: { 'title': title },
dataType: 'json',
success: function (data) {
deal_data(data);
}
})
})
var interval = null;
function deal_data(data) {
if(interval == null && data.count_down){
var end = data.count_down
secs = end % 60;
interval = setInterval(count, 1000);}
else if (interval != null) {
clearInterval(interval);
interval = null;
}
}
function count() {
console.log(secs);
secs -= 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.