How to stop interval function - javascript

I'm trying to stop with return syntax:
<script>
$(document).ready(function() {
setInterval(function() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
f(data.exists == 0){
alert("0");
} else {
alert("1");
return;
}
});
}, 5000);
});
</script>
The function verifies every 5 seconds if there exists data in my table.
I need to stop the function when data.exists == 1 ( the alert("1") ).

<script>
$(document).ready(function() {
var id;
id = setInterval(function() {
var idRefCopy = id; // You need this otherwise you'll get a reference exception
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
if(data.exists == 0){
alert("0");
} else {
alert("1");
clearInterval(idRefCopy);
return;
}
});
}, 5000);
});
</script>

You have to define the interval inside a variable, and then clear it. Try this:
<script>
$(document).ready(function() {
var interval = setInterval(function() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
if(data.exists == 0){
alert("0");
} else {
clearInterval(interval);
}
});
}, 5000);
});
</script>
You have a typo in the code (i have fixed it here, its a "f" instead of "if" ;) Hope this helps.

You need to clear your interval, this will prevent your function from being fired again. See this for interval reference.
This should be your code:
$(document).ready(function() {
var i = setInterval(function() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
f(data.exists == 0) {
alert("0");
} else {
alert("1");
clearInterval(i);
}
});
}, 5000);
});

How about clearInterval?
var myVar = setInterval(function(){myTimer()},1000);
function myTimer()
{
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction()
{
clearInterval(myVar);
}
source: W3Schools

I strongly suggest you do not hit your server unless you know your ajax was done
This example will check, but only after the server returned
var counter = 0;
function checkData() {
var url = "../view/anychange.php";
$.getJSON(url, function(data) {
if (data.exists == 0) {
$("#someContainer").html("Not yet on attempt #"+(counter++));
setTimeout(checkData,5000);
} else {
$("#someContainer").html("found on attempt #"+(counter++));
}
});
}
$(function() {
checkData();
});

Related

Reset jquery setTimeout after second Click on Button

I got a problem that wastes more and more time. Now I want to ask you guys to help me out. I really think it's not a big thing but I can't find the solution:
I have two code snippets, both really similar:
$(function () {
$('.plus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal)) {
$qty.val(currentVal + 1);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
var timeout = setTimeout(function () {
$.overlay.open();
form.submit();
}, 2000);
});
}
});
$('.minus--article').on('click', function () {
var $qty = $(this).closest('form').find('input[name="sQuantity"]');
var currentVal = parseInt($qty.val());
if (!isNaN(currentVal) && currentVal > 0) {
$qty.val(currentVal - 1);
window.clearTimeout(timeout);
$('.change-quantity--form').submit(function (e) {
var form = this;
e.preventDefault();
setTimeout(function () {
$.overlay.open({
closeOnClick: false
});
form.submit();
}, 2000);
});
}
});
});
I just want to reset the timeout after a click on one of the buttons.
var time;
}, 2000); use this-> }, time);
$(".test").on("click", function(){
time = 0;
});

Compare data returned from AJAX with div data

I would like to compare data to determine if the div needs to be reloaded.
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
var $original = $elem.html();
$.ajax({
cache : false,
url : '/inbox-header.php',
type : 'get',
success : function (data) {
var result = $.trim(data);
var resu = $.trim($original);
console.log(result);
if (result == resu) {
alert('a');
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
$elem.html(data);
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
reload('#inboxheader', 500);
});
// ]]>
When I show the output in the console it looks the same, but the alert never shows, so its always false.
UPDATE:
The output of those variables can be found here, unable to post them here..
http://pastebin.com/abfCk7pH
I dont know why but the trim function did not do his job.
this works:
$(function() {
function reload(elem, interval) {
var $elem = $(elem);
var $original = $elem.html();
$.ajax({
cache: false,
url: '/inbox-header.php',
type: 'get',
success: function(data) {
var opgehaaldedata = data.replace(
/(\r\n|\n|\r)/gm, "");
var orgineledata = $original.replace(
/(\r\n|\n|\r)/gm, "");
if (opgehaaldedata == orgineledata) {
//alert('a');
setTimeout(function() {
reload(elem, interval)
}, interval);
return;
} else {
$elem.html(opgehaaldedata);
setTimeout(function() {
reload(elem, interval)
}, interval);
return;
}
}
});
}
reload('#inboxheader', 500);
});

Clear setTimeouts applied by class.each operation that creates timeout

I'm sorry the title might not make much sense. I'm not sure how to word what i'm doing.
I have a class that I add to elements that uses HTML5 data attributes to setup a refresh timer. Here is the current code.
$(document).ready(function () {
$('.refresh').each(function() {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var preloader = element.data('show-loading');
var globalPreloader = true;
if (typeof preloader === 'undefined' || preloader === null) {
}
else if (preloader != 'global' && preloader != 'true') {
globalPreloader = false;
}
(function(element, url, interval) {
window.setInterval(function () {
if (!globalPreloader)
{
$('#' + preloader).show();
}
$.ajax({
url: url,
type: "GET",
global: globalPreloader,
success: function (data) {
element.html(data);
if (!globalPreloader) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
})(element, url, interval);
});
$.ajaxSetup({ cache: false });
});
Now I have elements that a user can click on the 'window' which removes it.
These elements can be tired to a timer that was set by the above code.
Code used to remove the element
$(".btn-close").on('click', function () {
var id = $(this).closest("div.window").attr("id");
if (typeof id === 'undefined' || id === null) {
} else {
$('#' + id).remove();
}
});
I need to now kill the timers created for the elements removed.
What is the best way to do this?
Not clear on how you clear them so I do them all here at the end.
$(document).ready(function () {
$('.refresh').each(function () {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var showLoading = element.data('show-loading');
var preloaderID = element.data('preloader-id');
if (typeof showLoading === 'undefined' || showLoading === null) {
showLoading = true;
}
(function (element, url, interval) {
var timerid = window.setInterval(function () {
if (showLoading) {
$('#' + preloaderID).show();
}
$.ajax({
url: url,
type: "GET",
global: showLoading,
success: function (data) {
element.html(data);
if (showLoading) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
element.data("timerid",timerid );//add the timerid
})(element, url, interval);
});
$.ajaxSetup({
cache: false
});
$('.refresh').each(function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
});
Example: remove timer on a click
$('.refresh').on('click', function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
window.setIntervalreturns a handle for the timeout. You can use that to stop the timeout:
var handle = window.setInterval(function() {
window.clearInterval(handle);
}, 1000);
Hope that helps.
Here's a little demo of intervals and "interval assassins". It's a minimal example showing how you can clear intervals in a JavaScript-y way.
$('.start').click(function() {
var $parentRow = $(this).closest('tr')
var $stop = $parentRow.find('.stop')
var $val = $parentRow.children('.val')
// interval
var iid = setInterval(function() {
$val.text(+$val.text() + 1)
}, 10)
console.log(`New Target: ${iid}`)
// interval assassin
$stop.click(function() {
clearInterval(iid)
console.log(`Interval[${iid}] has been assassinated.`)
$(this).off('click')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</tr>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</table>
Just run the snippet to see a demo. Feel free to comment if you have any questions. You can set up multiple intervals by pressing start repeatedly and have them all be cleared at once with a single click of stop.

IE not activating Ajax

I have the following script on my page, in Chrome, it works perfectly, but IE is not getting into the success{} function of Ajax. It goes into the Complete{} function perfectly fine. When I tried to send the data variable through the Complete{} function, it just displays an [object Object] as the contents. What can I do to get this to function in IE?
$(document).ready(function () {
var totalstrings = "";
var totaltimes = "";
var trendstop = "false";
var firstrun = "true";
var url = "newtrend.aspx";
$('#fm1').attr('src', "http://somepage/page1/collecttrend.aspx");
(function worker() {
var rand;
$.ajax({
url: 'http://somepage/page1/gettrendvars.aspx',
success: function (data) {
if (totalstrings.length < data.length || data === "") {
alert("test1");
if (trendstop === "false") {
alert("test2");
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
},
complete: function (data) {
setTimeout(worker, 10000);
$.ajax({
url: 'http://somepage/page1/gettimevars.aspx',
success: function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
},
complete: function (data) {
}
})();
}
});
})();
});
Try adding a timestamp to your ajax requests, for some reason, IE caches it sometimes.
$.ajax({
url: 'http://somepage/page1/gettrendvars.aspx?timestamp='+ new Date().getTime(),
success: function (data) {
if (totalstrings.length < data.length || data === "") {
alert("test1");
if (trendstop === "false") {
alert("test2");
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
},
complete: function (data) {
setTimeout(worker, 10000);
$.ajax({
url: 'http://somepage/page1/gettimevars.aspx?timestamp=' + new Date().getTime(),
success: function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
},
complete: function (data) {
}
})();
}
});
Finally got it to work, in conjunction with Vinicius Souza's answer. Utilizing the $.get() command rather than the ajax(), and activating the timestamp to break the caching of IE.
Thanks Everyone!
(function worker() {
var rand;
$.get("http://somepage/page1/gettrendvars.aspx?timestamp=" + new Date().getTime(), {})
.done(function (data) {
if (totalstrings.length < data.length || data === "") {
if (trendstop === "false") {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totalstrings = data;
}
if (data === "") {
trendstop = "true";
} else {
trendstop = "false";
}
}
$.get("http://somepage/page1/gettimevars.aspx?timestamp=" + new Date().getTime(), {})
.done(function (data) {
if (totaltimes != data) {
var iframe = document.getElementById("fm1");
iframe.src = iframe.src;
totaltimes = data;
}
});
})
.fail(function () {
});
setTimeout(worker, 1500);
})();

How to call alert after all ajax requests are done?

I'm making in code a few requests with JQuery and get. It looks like:
$.get('address1', function() { ... });
$.get('address2', function() { ... });
$.get('address3', function() { ... });
// This code should be runned when all 3 requests are finished
alert('Finished');
So, are there any ways to detect whether there is still processing request and run marked code only when all 3 requests are finished.
Thanks.
You can make use of deferred objects [docs] introduced in jQuery 1.5:
$.when(
$.get('address1', function() { ... }),
$.get('address2', function() { ... }),
$.get('address3', function() { ... })
).then(function() {
alert('Finished');
});
Reference: jQuery.when
The jQuery learning center has a nice introduction to deferred objects / promises.
var isFinished = [];
$.get('address1', function() { isFinshed.push["address1"]; allDone(); });
$.get('address2', function() { isFinshed.push["address2"]; allDone(); });
$.get('address3', function() { isFinshed.push["address3"]; allDone();});
var allDone = function(){
if(isFinished.length < 3)return
alert('Finished');
};
var fin1 = false;
var fin2 = false;
var fin3 = false;
$.ajax({
url: "address1",
success: function(){
fin1 = true;
fnUpdate();
}
});
$.ajax({
url: "address2",
success: function(){
fin2 = true;
fnUpdate();
}
});
$.ajax({
url: "address3",
success: function(){
fin3 = true;
fnUpdate();
}
});
function fnUpdate(){
if(fin1 && fin2 && fin3){
alert('fin');
}
}
var count = 0;
$.get('address1', function() { count++; ... });
$.get('address2', function() { count++; ... });
$.get('address3', function() { count++; ... });
var int = setInterval(function() {
if (count === 3) {
clearInterval(int);
alert('done');
}
}, 10);

Categories