Reputation: 229
I simply want to clear previous interval and set a new one when an ajax call is made.
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. Such as;
setting the "interval" variable to null or to false,
window.setInterval,
writing the count function inside of setInterval,
writing the count function as a separate function outside of the ajax function,
But neither of the variations cleared the interval.
Later on I'll also need to clear the interval on keydown.
Upvotes: 1
Views: 413
Reputation: 229
After several changes to MarshalSHI's answer the code ended up like this:
$("#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;
}
Upvotes: 0
Reputation: 625
From your code, I will do like below (P.S. didn't test):
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);
}
})
})
Upvotes: 1