This question already has answers here:
How to stop "setInterval" [duplicate]
(4 answers)
Closed 8 years ago.
I have like...
<div id="div"></div>
<script src="jquery.js"></script>
<script src="updater.js"></script>
The updater I want to get data from my .php file, so probably something like...
setInterval(function() {
$.ajax({
type: "GET",
url: "test.php",
success: function(html) {
// html is a string of all output of the server script.
$("#div").html(html);
}
});
}, 5000);
Then, obviously enough the test.php's page will result.
But, I want to STOP the setInterval(); WHEN someone clicks on a comment button (textarea). I'm aware, there's some on here; but they're not working?
Window.clearInterval, It accepts an intervalID is the identifier of the repeated action you want to cancel. This ID is returned from setInterval().
Example
var interVal = setInterval(function() {
$.ajax({
type: "GET",
url: "test.php",
success: function(html) {
// html is a string of all output of the server script.
$("#div").html(html);
}
});
}, 5000);
clearInterval(interVal); //Call the method when you want to clear it.
The setInterval function will return an integer which identifies that interval. Save that integer for later use, and when you want to clear the interval pass it into clearInterval as an argument.
E.g.:
var myInterval = setInterval(function() {
$.ajax({
type: "GET",
url: "test.php",
success: function(html) {
// html is a string of all output of the server script.
$("#div").html(html);
}
});
}, 5000);
And then when you want to cancel it:
clearInterval(myInterval);
Reference:
http://www.w3schools.com/jsref/met_win_clearinterval.asp
You can use clearInterval. It takes the Id of interval & clears it.
Get your setInterval in a variable.
var interval = setInterval(function(){...},time);
After clicking on button just do
clearInterval(interval);
DEMO
Related
I have created an Interval that runs on every 2 seconds, when the page loads. Now, when I move to other page, the interval is cleared (Please check the code). Now what I want is when I move to the same tab again, the interval should start again.
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.
How can solve this issue?
Here's my code:
var zzz= setInterval(anewFunc, 2000);
function anewFunc(){
$(document).ready(function(){
var chatattr=$(".chatwindow").css("visibility");
var chattitle=$("#hideid").text();
if(chatattr=="visible"){
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle="+chattitle,
success: function(result9){
},
error: function(){
}
});
}
$(window).blur(function(){
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10){
// alert(result10);
},
error: function(){
}
});
clearInterval(zzz);
});
});
}
One thing I tried was that I wrote this whole code inside $(window).focus(//CODE) but the problem is that it doesn't run when the page is initially opened in any browser's tab.
Okay, the problem here is, the setInterval() doesn't execute at 0 seconds. It starts from 2 seconds only. So you need to make a small change:
Have the function separately.
Inside the ready event, start the timer, as well as run the function for the first time.
Remove the event handlers from the interval, or use just .one() to assign only once. You are repeatedly adding to the .blur() event of window.
Corrected Code:
function anewFunc() {
var chatattr = $(".chatwindow").css("visibility");
var chattitle = $("#hideid").text();
if (chatattr == "visible") {
$.ajax({
url: 'seen1.php',
type: 'post',
data: "ctitle=" + chattitle,
success: function(result9) {},
error: function() {}
});
}
$(window).one("blur", function() {
$.ajax({
url: 'session.php',
type: 'post',
success: function(result10) {
// alert(result10);
},
error: function() {}
});
clearInterval(zzz);
});
}
$(document).ready(function() {
var zzz = setInterval(anewFunc, 2000);
anewFunc();
});
Now what I want is when I move to the same tab again, the interval should start again.
You haven't started the setInterval() again.
$(document).ready(function () {
$(window).one("focus", function() {
var zzz = setInterval(anewFunc, 2000);
});
});
I currently have the below function which updates the data in a div when the page is refreshed and this works fine however i want to edit the function to make it constantly update say every 2 seconds without having to refresh the page. How would i go about doing this?
<script>
$(document).ready(function ajaxLoop() {
//-----------------------------------------------------------------------
// Send a http request with AJAX Jquery
//-----------------------------------------------------------------------
$.ajax({
url: 'getOrderStatus.php', // Url of Php file to run sql
data: "",
dataType: 'json', //data format
success: function ajaxLoop(data) //on reciept of reply
{
var OrdersSubmitted = data[0].SUBMITTED; //get Orders Submitted Count
var OrdersFulfilled = data[0].FULFILLED; //get Orders Fulfilled count
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#OrdersSubmitted').html("SUBMITTED:" + OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:" + OrdersFulfilled); //Set output html divs
}
});
});
</script>
You can chain setTimeout calls to achieve this:
$(document).ready(function() {
function updateOrders() {
$.ajax({
url: 'getOrderStatus.php',
dataType: 'json',
success: function ajaxLoop(data) {
var OrdersSubmitted = data[0].SUBMITTED;
var OrdersFulfilled = data[0].FULFILLED;
$('#OrdersSubmitted').html("SUBMITTED:"+ OrdersSubmitted);
$('#OrdersFulfilled').html("FULFILLED:"+ OrdersFulfilled);
setTimeout(updateOrders, 2000);
}
});
});
The alternative is setInterval(), however if the requests slow down this can lead to calls being queued, which will eventually lead to memory issues.
You need to add a repeating event to call your updateOrders function. Like:
function startUpdateOrdersTimes() {
setInterval(function() {
updateOrders();
}, 2000);
//Call now (otherwise waits for first call)
updateOrders();
}
Using "window.setInterval" (https://developer.mozilla.org/en/docs/Web/API/window.setInterval) you can repeatedly execute a function at a specified time interval.
function SomeFunction()
{
$.ajax({...});
}
window.setInterval(SomeFunction,2000);
This would execute SomeFunction every 2 seconds
Hope this helps
timerupdateorders = setInterval(function() {
ajaxLoop();
}, 2000);
You may use
clearInterval(timerupdateorders);
to end the timer
I'm making a conversation system where 2 people can chat with each other. I've made an AJAX function which updates the DIV box containing the messages every 2 seconds.
This is working as intended, after a user have written a message. Why isn't the AJAX call being run right away?
// SET AUTORUN updateMessages() EVERY 2 SECONDS
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
// UPDATE #mail_container_conversation
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
success: function(data){
$("#mail_container_conversation").html(data);
}
});
}
// SEND NEW MESSAGE
$(function(){
$("#mail_send").submit(function(){
dataString = $("#mail_send").serialize();
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: dataString,
success: function(data){
updateMessages();
$(".mail_conversation_answer_input").val('');
}
});
return false;
});
});
You should provide functions instead of strings to setTimeout/setInterval functions. And also there's no need for you to set interval on window load event. You can just keep it as part of DOM ready:
$(function() {
updateMessages(); // don't wait 2 seconds for first update
setInterval(updateMessages, 2000); // update every 2 seconds
});
Everything else seems to should work as expected as long as your posback work when no data is being received (ref dataString).
I hope you do realise that you're using implied globals and understand why that may be a big problem (ref dataString again).
How I would rewrite your code
I would rewrite your whole code into the following that removes implied global variable dataString, doesn't pollute global scope with additional functions and uses setTimeout instead of interval which may in some cases be problematic (although in your case since it' only runs every 2 seconds it shouldn't be a problem if there's no additional very complex client-side script execution)
I've kept everything within function closure local scope:
$(function() {
var timeout = null;
var form = $("#mail_send").submit(function(evt){
evt.preventDefault();
$(".mail_conversation_answer_input", form).val("");
updateMessages();
});
var updateMessages = function() {
// we don'w want submit to interfere with auto-updates
clearTimeout(timeout);
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: form.serialize(),
success: function(data){
$("#mail_container_conversation").html(data);
timeout = setTimeout(updateMessages, 2000);
}
});
};
// start updating
updateMessages();
});
This code requires your server side (processing on /mail/send) to understand that when nothing is being posted (no data) that it doesn't add empty line in the conversation but rather knows that this is just an update call. This functionality now uses only one server-side URL and not two of them. If you'd still require two, then this code should do the trick:
$(function() {
var timeout = null;
var url = {
update: "<?php echo site_url();?>mail/ajaxupdate/<?php echo $user;?>",
submit: "<?php echo site_url();?>mail/send",
use: "update"
};
var form = $("#mail_send").submit(function(evt){
evt.preventDefault();
url.use = "submit";
$(".mail_conversation_answer_input", form).val("");
updateMessages();
});
var updateMessages = function() {
// we don'w want submit to interfere with auto-updates
clearTimeout(timeout);
$.ajax({
type: "POST",
url: url[url.use],
data: form.serialize(),
success: function(data){
$("#mail_container_conversation").html(data);
url.use = "update";
timeout = setTimeout(updateMessages, 2000);
}
});
};
// start updating
updateMessages();
});
If the rest of your code work, the problem probably is withing this code:
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
There is no need to attach it to window.onload, since you already wrapped it in a DOM-ready callback.
Remove the single-quotes and the parenthesis from within your call to setInterval
The DOM-ready callback can be shorten, by just passing a function to the jQuery-method.
Try this instead:
$(function () {
setInterval(updateMessages, 2000);
});
Further improvements - Avoid intervals with AJAX:
When dealing with AJAX, you should avoid using intervals, as you may end up stacking calls to the server, if the server takes more than two seconds to respond. setInterval will not care if your server had time to respond or not, it will keep calling it every 2 seconds no matter what.
I suggest that you use a timeout instead, and start a new timeout in the complete-callback of the Ajax-call.
In your case, it could look something like this:
$(function () {
// Make the first call immediately when the DOM is ready
updateMessage();
});
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
success: function(data){
$("#mail_container_conversation").html(data);
// Make a new call, 2 seconds after you've
// received a successful respose
setTimeout(updateMessages, 2000);
}
});
}
The problem is that updateMessages() tries to send datastring to the server, but this doesn't get filled in until the .submit() function runs.
I don't know what you should put in there, since I don't know what the mail/ajaxupdate script expects. If this is called when nothing happens, I suspect no form data is needed at all, so you can give an empty string.
I'll bet if you checked the Javascript console you'd see some error messages about trying to serialize undefined.
give a try with
$(document).ready(function() {
setInterval('updateMessages()', 2000);
});
You don't need the window.onload in your document ready call.
$(document).ready(function() {
setInterval('updateMessages()', 2000);
});
That should be enough to get it started.
As it is now, once the DOM is ready, you're then asking it to wait for the window to load.. but by that point it's already loaded, so nothing happens.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery Ajax request every 30 seconds
I know we can load a part of page on some event. I also know we can load whole web page every specified time, but I wanted to know how to load a part of page every 30 seconds.
function refreshPage() {
$.ajax({
url: 'ajax/test.html',
dataType: 'html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
window.setTimeout(refreshPage, 30000);
}
});
}
window.setTimeout(refreshPage, 30000);
Using setTimeout has the advantage that if the connection hangs for some time you will not get tons of pending requests since a new one will only be sent after the previous one finished.
function load_content(){
setTimeout(function(){
$.ajax({
url: 'ajax/example.html',
dataType: 'html',
success: function(data) {
$('.result').html(data);
load_content();
}
});dataType: 'html',
},30000);
}
load_content();
jQuery has already a build in functionality to replace a element's content by a remote file, called load(). With load() you can use this oneliner:
window.setTimeout($('#refresh').load('/remote/content.html'), 30000);
#refresh is the id of the element to refresh, /remote/content.html is the remote content.
$(function() {
setInterval(function() {
getData(); // call to function
}, 30000 ); // 30 seconds
});
// define your function here
function getData() {
var url ="/mypage.php?type=load_data";
var httpobj = $.ajax({url:url,async:false}); // send request
var response = httpobj.responseText.trim(); //get response
$('#myDiv').html(response); // display data
}
If you are using jQuery you can use the load() method
setInterval(function(){
$('#some-kinda-container').load('/some/kinda/url.html #bit-you-need');
}, 30000);
My scripts are working perfectly fine. However, the content does not refresh itself to get new data. Why is it so?
function updateMsg() {
$.ajax({
url: "/recent/notifications/",
cache: false,
success: function(html){
$("#profile_notifarea_msgbox").html(html);
}
});
setTimeout('updateMsg()', 4000);
}
updateMsg();
Your setTimeout can reference updateMsg directly instead of using a string:
var timeout;
function updateMsg() {
$.ajax({
url: "/recent/notifications/",
cache: false,
success: function(html){
$("#profile_notifarea_msgbox").html(html);
timeout = setTimeout(updateMsg, 4000);
}
});
}
updateMsg();
function stopUpdate() {
clearTimeout(timeout);
}
To stop the continuous update you save a reference to the setTimeout in a variable and then call clearTimeout and pass in that variable. In this example, you would just call the function stopUpdate() to cancel the updates.
when you use ajax with jQuery try to always put an error function, in this way you can identify if something is wrong with the request