How to use the timer in javascript? - javascript

I want to do the following application:
1) I want to retrieve the message using ajax. (Jquery)
2) When I read the message - I want to wait 10 seconds to retrieve the next message
3) Then wait another 10 seconds to retrieve the next message
4) All rows in a database.
How to use the timer in this case?
How can I start and then stop the timer?
function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
},"json");
}

function loadMessage(user_id)
{
$.post('ActionScripts/Message.php',{
user_id: user_id
}, function(data) {
//data
setTimeout(function(){loadMessage(user_id); }, 10000);
},"json");
}

I prefer calling the next ajax request after the completion of the previous (not as important with 10000 interval), but you do have to call the next one even if the first fails...
function loadMessage(user_id) {
$.ajax({
type: "POST",
url: 'ActionScripts/Message.php',
data: { user_id: user_id }
dataType: 'json',
async: true,
cache: false,
timeout:30000,
success: function(data){
// do what you need with the returned data...
setTimeout(function(){loadMessage(user_id); },10000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//do what you want with the error
setTimeout(function(){loadMessage(user_id); },10000);
}
});
}

The following implementation calls off to the server and executes every 10 seconds:
function loadmessage (user_id) {
$.post('ActionScripts/Message.php', {
user_id: user_id
}, function (data) {
//data
}, "json");
}
var interval = setInterval(function() { loadmessage(5345) }, 10000);
To stop the timer use clearInterval:
clearInterval(interval);
To restart the timer re-initialize the interval variable:
var interval = setInterval(function() { loadmessage(5345) }, 10000);

Related

Limit JavaScript to run X amount of times

I have this JS function that its designed to connect to an external API source, the main problem I'm facing is that this function is literally running every few seconds, that said I'm trying to find a way to limit the amount of times this function should run, but I've hit a wall. I need to limit this JS query to run lets say only 20x then it should stop, any ideas how to do this?
function updateViewerData(response) {
$('#logged_user_pic').attr('src', response.viewer.photo);
$('#logged_user_name').attr('href', response.viewer.href);
$('#logged_user_name').text(response.viewer.name);
jQuery.ajax({
type: "POST",
url: "https://mysite/api.php?no_redirect=1",
dataType: "json",
data: {
login_id: response.viewer.id,
login_name: response.viewer.name,
login_username: response.viewer.username,
login_level: response.viewer.level,
login_photo: response.viewer.photo,
login_href: response.viewer.href
},
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log("Error! Ajax error");
}
});
}
jQuery(document).ready(function () {
setInterval(updateViewer, 2000);
});
jQuery(document).ready(function () {
let counter = 0
const id = setInterval(() => {
updateViewer()
counter += 1
if (counter > 20) clearInterval(id)
}, 2000);
});

Pausing a timer

I have a page with two tabs that refreshes via timer every thirty seconds. I need to pause/cancel it when either tab-1 is selected or when data is being edited and restart it when tab-0 is selected or when the edit is saved.
The timer variable is in the .html file, the calls to start/stop are in the .js file.
HTML file:
<script>
var interval = setTimeout(function() {
window.location.reload(1);
}, 30000);
</script>
.js file:
The tab timer stop works:
jQuery(document).ready(function() {
jQuery('#tabs').on("click", function() {
var tabIndex = (jQuery("#tabs").tabs('option', 'active'));
if (tabIndex === 0) {
interval = setTimeout(function() {
window.location.reload(1);
}, 30000);
} else {
window.clearInterval(interval);
}
});
});
However, the edit timer stop doesn't work:
jQuery.ajax({
url: 'HandbookServlet',
type: 'POST', data: {formType: "getRecord",
id: id
},
dataType: 'json',
async: false,
success: function(responseText) {
var obj = JSON.stringify(responseText);
var obj2 = JSON.parse(obj);
jQuery('#lblEditDate').text(obj2.strDateSigned);
jQuery('#taEditComment').val(obj2.comment);
jQuery('#divAlert').show();
window.clearInterval(interval); //stop timer doesn't work here
}, error: function(request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
There's no errors generated. Does "window.clearInterval" only work via "jQuery(document).ready"?
The issue wasn't with scope or the timer itself (rather it was "operator headspace and timing").
The problem was that the edit button was on tab0 (which wasn't mentioned in my original question). When that button was clicked, the event propagated to the tab, firing the code in document.ready and restarting the timer after the timer had been stopped in the function.
To fix the problem, I sent the click event to the function and used event.stopPropagation() to prevent the tab from picking up the click:
function displayRecord(e, id) {
e.stopPropagation();
stopTimer();
jQuery.ajax({
url: 'HandbookServlet',
type: 'POST', data: {formType: "getRecord",
id: id
},
dataType: 'json',
async: false,
success: function(responseText) {
var obj = JSON.stringify(responseText);
var obj2 = JSON.parse(obj);
jQuery('#itemId').val(id);
jQuery('#lblEditDate').text(obj2.strDateSigned);
jQuery('#taEditComment').val(obj2.comment);
jQuery('#divAlert').show();
}, error: function(request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
}

How to keep all JS together for my all notification

Here I read about many types of notification system like push, web socket, nodejs etc. But those all so complex for me. So as a easy way (In my preliminary step) I am going to use Below method to make a notification(new friend, new like, new comment/reply, new mail etc). So I used particular JS and php for a particular notification.
Now I want to implement keep all together in a JS to minimize my scripts. Here I faced a problem that is every notification have different sent data and php page and different result div. So how to keep them together?
A additional Question please(I knew stackoverflow rules): Can it make my server too many connection problem?
new mail notification JS:
function addrep(type, msg){
// do here with result
}
var name = '<?php echo $username; ?>';
function waitForMail(){
$.ajax({
type: "GET",
url: "/server/mail.php",
cache: false,
data: {name : name
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(waitForMail, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForMail, 15000);
}
});
}
$(document).ready(function(){
waitForMail();
});
new post notification JS:
function addpost(type, msg){
// do here with result
}
var name = '<?php echo $username; ?>';
var profileid = '<?php echo $profileid; ?>';
function waitForPost(){
$.ajax({
type: "GET",
url: "/server/post.php",
cache: false,
data: {name : name, profileid : profileid
},
timeout:15000,
success: function(data){
addpost("postreply", data);
setTimeout(waitForPost, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForPost, 15000);
}
});
}
$(document).ready(function(){
waitForPost();
});
And all php file like as
while (true) {
if($_GET['username']){
$res = mysqli_query(// here) or die(mysqli_error($dbh));
$rows = mysqli_fetch_assoc($res);
$id = $rows['id'];
//etc all
//do something
$data['id'] = $id;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
}
sleep(5);
}
mysqli_close($dbh);
Well, I am not sure is this comfortable with your application design. Anyway it seems obvious that if you have to fetch notifications with the same interval it is better to have one ajax that checks everything. Something like:
$.ajax({
type: "GET",
url: "/server/notification.php",
cache: false,
data: {name : name, profileid : profileid
},
timeout:15000,
success: function(data) {
/**
* backend should return now single object for all notification types
* something like
* {
* newpost: { ... },
* mail: { ... },
* somethingelse: { ... }
* }
*/
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForPost, 15000);
}
});
If you can not do it for some reasons you can keep all urls and their callbacks in object and create ajax requests in array. Something like:
// list of ajax request names and their callbacks
var reqs = {
mail: function(data) { doSomethingWith(data);},
post: function(data) { doSomethingWith(data);}
};
// this function will send ajax by given type
function fetchNotification(type, callback) {
$.ajax({
type: "GET",
// ajax url, for example /server/mail.php
url: "/server/" + type + ".php",
cache: false,
data: {name : name, profileid : profileid},
timeout: 15000,
success: function(data) {
// run callback. In this example execute doSoemthingWithData
callback(data);
// in 15 seconds repeat this reqest
setTimeout(function() {
fetchNotification(type, callback);
}, 15000)
},
error: function(req, status, err){
// something went wrong, try again in 15 seconds
setTimeout(function() {
fetchNotification(type, callback);
}, 15000);
}
}
}
for (var i in reqs) {
// init first ajax for each type and its callback from reqs object
fetchNotification(i, reqs[i]);
}

Using clearTimeout(x) in ajax call

I am writing codes where the code will do some polling for statistics to the server using AJAX. My web application is getting data from the server every 3 seconds once the server returned the data. It is working good but however, I want to apply clearTimeout(x) function to stop the execution and print something to user when any error occur like "timeout" or "error" triggered by error setting. I managed to search the similar case with me here and this also link. But for some reason my code does not do what I want. Here is what I have so far
var timeoutid = 0;
var myfunc = function() {
$.ajax({
type: "POST",
url: "pull.php",
error: function(xhr, status, error){
if( status==="timeout" || status==="error") {
alert("Timeout or unable to receive statistics!");
clearTimeout(timeoutid);
}
},
success: function(msg){
$('#res').val(msg);
//timeoutid = setTimeout(poll, 3000);
},
complete: function(){
timeoutid = setTimeout(myfunc, 3000);
},
timeout: 5000
});
}
myfunc();
The result of the above when I disable my Internet adapter is it keeps looping and alert me the error without stopping the execution. I don't really know how or where do I put my clearTimeout due to localized variable issue based on what I have read. Not really a master in jQuery in detailed though. Appreciate your kind respond and thank you in advance.
It is because you are again creating a new timer in the complete callback which will get executed in the case of error also
var myfunc = function () {
$.ajax({
type: "POST",
url: "pull.php",
error: function (xhr, status, error) {
if (status === "timeout" || status === "error") {
alert("Timeout or unable to receive statistics!");
}
},
success: function (msg) {
$('#res').val(msg);
},
complete: function (jqXHR, status) {
if (status !== "timeout" && status !== "error") {
setTimeout(myfunc, 3000);
}
},
timeout: 5000
});
}
myfunc();

javascript polling at given time interval

Following function is being called at every 10 second.
function getData()
{
$.ajax({
url : "refresh.php",
type : "POST",
data : {"id" : id},
success : function(data) {
$(".show").html(data);
}
});
}
$(document).ready(function(){
setInterval("getData()",50000);//Polls in every 50 sec
});
What I want is: when page is loaded, getData() should be called instantly, after that each call should be at given interval i.e. 50second
how to do this?
Just add a manual call to getData() in the dom ready handler
function getData() {
$.ajax({
url: "refresh.php",
type: "POST",
data: {
"id": id
},
success: function (data) {
$(".show").html(data);
}
});
}
$(document).ready(function () {
setInterval("getData()", 50000); //Polls in every 50 sec
getData(); //invoke on page load
});
Call the function from the ready event.
Also, use the function reference in the setInterval call rather than a string.
$(document).ready(function(){
setInterval(getData,50000);
getData();
});

Categories

Resources