Pausing a timer - javascript

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);
}
});
}

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);
});

AjaxSubmit submits form twice (or three times or 20 times)

I'm new here and new to JS :-)
I'm using AJAX SUBMIT (jquery) to send files to my CDN.
the first time - everything is ok, the file is sent and received.
second time: the file is sent and received, only it does that twice.
and the third time its three times etc...
that's the console of the second time: https://prnt.sc/tluygu
as you can see, it submits twice.
That's the code of the submission: (it's in a modal)
$(document).on('click', '.add-video-btn', function() {
$('#file').val('');
$('#file-upload').trigger('reset');
$('#video-uploading-modal').modal({
backdrop: 'static',
keyboard: false
});
$('#upload-btn').on('click', async function() {
var vidRes = await getOneTimeUploadUrl();
console.log(vidRes.result.uploadURL);
var oneTimeUrl = vidRes.result.uploadURL;
$('#file-upload').ajaxSubmit({
url: oneTimeUrl,
beforeSubmit: function(formData, formObject, formOptions) {
console.log(formData);
$('.progress').slideDown();
},
beforeSend: function() {},
uploadProgress: function(event, position, total, precentComplete) {
$('.progress-bar').css('width', precentComplete + '%');
$('.progress-bar').html('%' + precentComplete);
},
success: function(response) {
console.log(response);
alert('success');
},
});
});
});
The problem is that every time the modal is opened, a new submit listener gets added. To fix your problem, you need to split the event handlers:
Start with the modal click listener:
$(document).on('click', '.add-video-btn', function() {
$('#file').val('');
$('#file-upload').trigger('reset');
$('#video-uploading-modal').modal({
backdrop: 'static',
keyboard: false
});
});
Then, set the submit listener sepparately:
$('#upload-btn').on('click', async function() {
var vidRes = await getOneTimeUploadUrl();
console.log(vidRes.result.uploadURL);
var oneTimeUrl = vidRes.result.uploadURL;
$('#file-upload').ajaxSubmit({
url: oneTimeUrl,
beforeSubmit : function(formData, formObject, formOptions) {
console.log(formData);
$('.progress').slideDown();
},
beforeSend : function() {
},
uploadProgress : function(event, position, total, precentComplete) {
$('.progress-bar').css('width', precentComplete + '%');
$('.progress-bar').html('%' + precentComplete);
},
success: function(response) {
console.log(response);
alert('success');
},
});
});
That should solve your issue. Hope you've found this helpful.

Jquery Ajax Upload with progress is reloading page

I have strange stuf with a Jquery form submit.
After the upload completed, the page is reloading even in the server has not finished to process.
The server just return a json succes status, so It's not on server side.
Here"s the code:
$form.on('submit', function (e) {
console.log('Submit form ' + fileNumber);
if ($form.hasClass('is-uploading')) return false;
$form.addClass('is-uploading').removeClass('is-error');
if (isAdvancedUpload) {
e.preventDefault();
e.stopPropagation();
var ajaxData = new FormData($form.get(0));
var $input = $form.find('input[type="file"]');
if (fileToUpload) { ajaxData.append($input.attr('name'), fileToUpload); }
console.log('FileTo Upload: ' + fileToUpload);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: 'json',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
},
cache: false,
contentType: false,
processData: false,
beforeSend: function (xhr,settings) {
},
complete: function (xhr, status) {
xhr.
//$form.removeClass('is-uploading');
//fileNumber++;
//fileToUpload = droppedFiles[fileNumber];
//if (fileToUpload) { $form.submit(); }
},
success: function (data,status,xhr) {
//$form.addClass(data.success === true ? 'is-success' : 'is-error');
//if (!data.success) $errorMsg.text(data.error);
},
error: function (xhr,status,error) {
}
});
} else {
// ajax for legacy browsers
}
});
The issue is here:
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', progress, false);
}
return myXhr;
If I remove return myXhr The page is not reloading after upload, but I have no progress report.
I don't know what to do to prevent reloading.
Thanks.
I found out the issue.
There was no worry with the xhr object.
The issue was coming from Visual Studio Browser Link.
After shuting it down, everything worked perfectly.
Browser link, for an obvious reason was fire a reload of the page.
Will see with the ASP.NET Core team
try change buttin type submit to button and implement click function
eg:
$( "#buttonID" ).click(function() {
//your code
});

How to save a variable to the server using jQuery

I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...

How to use the timer in 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);

Categories

Resources