Reputation: 1776
In this code snippet i make a http call every 6 seconds to see if some data has arrived on the sever. (I could not use websockets or Server-sent events so i had to do it this way).
The thing is that when data!= '-1'
and myaddress == data.address
sometimes i get two popup windows instead of one. I don't know what can be wrong in this code but it is happening....
var id;
id = setInterval(function() {
$.get( 'https://example.com?dir='+myaddress,{}, function(data) {
if (data != '-1') {
if (myaddress == data.address) {
clearInterval(id);
//(..whatever..)
popitup(); // show's a new pop up window
}
return;
}
});
}, 6 * 1000);
Upvotes: 0
Views: 2280
Reputation: 6914
because the ajax request MAY be slow sometimes but the interval of your timer works each 6 seconds ALL the time. fix it like that:
var id, ajax;
id = setInterval(function()
{
if (ajax) return;
$.get( 'https://example.com?dir='+myaddress,{}, function(data)
{
if (data != '-1')
{
if (myaddress == data.address)
{
clearInterval(id);
//(..whatever..)
popitup(); // show's a new pop up window
}
return;
}
ajax = false;
});
ajax = true;
}, 6 * 1000);
Upvotes: 1
Reputation: 33399
The AJAX request is being made before the interval is cleared, so it's queued, and both end up being executed. You can add a check to see if the interval has been cleared with a bit of extra code:
var id;
id = setInterval(function() {
$.get( 'https://example.com?dir='+myaddress,{}, function(data) {
if (data != '-1') {
if (myaddress == data.address && id) { // make sure id isn't undefined
id = clearInterval(id); // reset id to undefined
//(..whatever..)
popitup(); // show's a new pop up window
}
return;
}
});
}, 6 * 1000);
Upvotes: 1