How to get the time after clicking the button - javascript

I'm trying to get the time between when the user clicks the start button and the stop button. I was able to start and stop the time but I can't get the time. I'm using ajax success function to call clearInterval function to stop the time so when I successfully inserted my data. The time will stop and I need to get the time after the stop button is clicked.
I just need to get the variable cons. below is my code:
$(".start").click(function() {
var sec = 0;
var cons = 0;
siID = setInterval(function() {
cons = sec++;
console.log(cons);
}, 1000);
});
$('.stop').click(function() {
$.ajax({
url: "Register_c/register_data",
method: 'POST',
async: false,
data: {
registration: {
TIN: '123'
}
},
success: function(data) {
window.clearInterval(siID); //stops the counting
alert(cons); //here i can't get the variable cons
},
error: function(xhr, status, error) {
alert('failed');
}
});

As many have pointed out, you need to move cons into the global scope, I'd also recommend using performance.now() as it gives a more accurate time over Date.now(). Another point, you want to know the difference before calling the AJAX request otherwise it's more of the time difference between the user clicking start then stop and then the request finishing rather than just the user clicking start and then stop.
var cons = null;
$(".start").click(function () {
cons = performance.now();
});
$('.stop').click(function () {
alert(performance.now() - cons); //Difference in Milliseconds
$.ajax({
url: "Register_c/register_data",
method: 'POST',
data: {
registration: {
TIN: '123'
}
},
success: function (data) {
},
error: function (xhr, status, error) {
alert('failed');
}
});
});
var cons = null;
$(".start").click(function() {
cons = performance.now();
});
$('.stop').click(function() {
console.log("Call to stop took " + ( performance.now() - cons) + " milliseconds.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="start">Start</button>
<button class="stop">Stop</button>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var sec =0;
var cons =0;
var start = $('#start').click(function() {
siID = setInterval(function() {
cons = sec++;
console.log(cons);
}, 1000);
return cons;
});
$('#stop').click(function() {
alert(cons);
$.ajax({
url: "Register_c/register_data",
method: 'POST',
async: false,
data: {
registration: {
TIN: '123'
}
},
success: function(data,start) {
window.clearInterval(siID); //stops the counting
alert(start); //here i can't get the variable cons
},
error: function(xhr, status, error) {
alert('failed');
}
});
});
});
</script>
</head>
<body>
<button id="start">start</button>
<button id="stop">stop</button>
</body>
</html>
I have added the start function and it returns the cons and able to display that in an alert on clicking the stop function.

Your variable cons is a local scope so it is not available in another method where you are trying to display it, that is reason why you should move it up to a global scope
A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it, and that's what you need.
But also I would recommend you to use console.time (non-standard) to measure execution time of your registration method:
console.time('someFunction');
someFunction(); // run whatever needs to be timed in between the statements
console.timeEnd('someFunction');
or you could use the standard performance.now() API, like so:
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
I hope this will help you..

Related

Ajax Iterate - Repeat the AJAX Call every 3 seconds

AJAX call instead of .click load - I would like the ajax to run every 3 seconds till the end of Total_Records. Here is my AJAX code which runs .click of a button.
I am passing two variables
1. id number
2. Total_Records
I would like the ajax to iterate a number of times = Total_Records.
Any suggestions are highly appreciated.
$(document).ready(function() {
$(document).on('click', '.show_more', function() {
var ID = $(this).attr('id');
var lim = $(this).attr('Total_Records');
$.ajax({
type: 'POST',
url: 'moreajax.php',
data: {
'id': ID,
'lim': lim
},
success: function(html) {
setTimeout(function() {
$('#show_more_main' + ID).remove();
$('.postList').append(html);
}, delay);
},
});
});
});
Method 2) Please kindly read and recommend any better way or script improvement with examples please. this will benefit everyone.
Note: I believe this method would be a great enhancement and re-usable to lots of people who are looking for interval runs.
The only issue is the cancel button .click is not stopping the ajax call.
$('#cancel').click(function() {
cancel = true;
});
$(function() {
//If cancel variable is set to true stop new calls
if (cancel == true) return;
var RecordsInterval = 10 * 1000;
var fetchRecords = function() {
console.log('Sending DATA AJAX request...');
$.ajax({
type: "POST",
url: "fetchRecords.php",
data: {
'id': ID,
'lim': lim
}
}).done(function(html) {
$('#show_more_main' + ID).remove();
$('#postList').append(html);
alert("You got it champ")
console.log('success');
console.log('Waiting ' + (RecordsInterval / 1000) + ' seconds');
setTimeout(fetchRecords, RecordsInterval);
}).fail(function() {
console.log('error');
alert("error Champ");
return;
});
}
// Fetch Records immediately, then every 10 seconds AFTER previous request finishes
fetchRecords();
});

setInterval keeps stacking even with clearInterval

I'm making a simple punch in / punch out timer.
Problem im facing is that it works perfectly on page load but when the user clicks end_work_btn then begin_work_btn, the timer kinda stacks the initial value and the new one starting from 0 so it's trying to display both. It keeps stacking everytime they click the buttons until page reload when it resets.
I've done a bunch of reading and figured clearInterval(timer) would do it but no go so assuming i'm not using it correctly or i'm way off the ball on whats wrong here.
Here's what I got so far
<button id="begin_work_btn">Begin Work</button>
<button id="end_work_btn"><span id="hours"></span>:<span id="minutes"></span>:<span id="seconds"></span></button>
<script>
var emp_id = '2';
var timer = null;
function reset_timer(time){
var sec = time;
clearInterval(timer);
function pad ( val ) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval( function(){
$("#seconds").html(pad(++sec%60));
$("#minutes").html(pad(parseInt(sec/60,10)%60));
$("#hours").html(pad(parseInt(sec/3600,10)));
}, 1000);
}
reset_timer(<?php echo $existing_time;?>);
$("#begin_work_btn").click(function(){
$.ajax({
type: "post",
url: "<?php echo $url;?>process.php",
data: "agent_id="+emp_id+"&action=begin_work",
success: function(data){
var sec = 0;
reset_timer(sec);
$('#begin_work_btn').hide();
$('#end_work_btn').show();
}
});
});
$("#end_work_btn").click(function(){
$.ajax({
type: "post",
url: "<?php echo $url;?>process.php",
data: "agent_id="+emp_id+"&action=end_work",
success: function(data){
$('#end_work_btn').hide();
$('#begin_work_btn').show();
}
});
});
</script>
Pretty simple, scope is different. In your code you have two variables named timer. The one inside the function is created each time reset_timer is called. One outside never gets a value. So each time you call the function, another instance of timer is created.
var timer = null; //<-- outside
function reset_timer(time){
clearInterval(timer);
var timer = setInterval( ... , 1000); //<--redefined inside so each time, it creates new variable
}
You basically have this:
function reset_timer(time){
var timer;
clearInterval(timer);
timer = setInterval( ... , 1000);
}
It should not be defined with var. This way it updates the variable defined outside of the function each time it is called.
var timer = null;
function reset_timer(time){
if (timer) clearInterval(timer);
timer = setInterval( ... , 1000); //<--no more var
}

Looping ajax calls until button is pressed

document.getElementById("uploadUpdate").addEventListener("click", function() {
intervalVarUpload = setInterval(function () {
console.log("Updating table..");
Object.keys(arrExplores).forEach(function (key) {
if(arrExplores[key][2] != "Not"){
//remoteArrUpdate makes a ajax call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}, 2000);
console.log("Interval started!");
});
document.getElementById("uploadStop").addEventListener("click", function() {
clearInterval(intervalVarUpload);
});
function remoteArrUpdate(id, key) {
$.ajax({
url: 'https://offcloud.com/api/remote/status',
data: {'requestId' : id},
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data) {
arrExplores[key] = [arrExplores[key][0],key,data.status.requestId,data.status.status, data.status.fileSize];
explorArrToTable();
},
error: function() {
console.log('Failed!');
}
});
}
So, at the moment, a uploadUpdate button is clicked and an interval is started to go through an array and make a ajax on every object and update that object. However, I don't want to use an interval because sometimes the next interval will start before the previous is finished and sometimes there is a long wait time. I want the next interval to start as soon as the previous interval has either successfully or unsuccessfully finished all ajax calls, to start at the beginning of the array again and start making the same ajax calls, until the uploadStop button is pressed. How would i change the two button functions to do this?
Just tried to mimic your ajax calls using a setTimeout. You could use it in your ajax success / failure. I think, you need some code refactoring to accomplish this. Hope this helps / point you in the right direction.
var intervalVarUpload;
document.getElementById("uploadUpdate").addEventListener("click", function() {
uploadUpdate();
});
function uploadUpdate() {
//Start the Interval
intervalVarUpload = setInterval(doSomething, 2000);
console.log("Interval started!");
}
document.getElementById("uploadStop").addEventListener("click", function() {
console.log("Interval Stopped");
//Clear the Interval
clearInterval(intervalVarUpload);
});
function doSomething() {
//Clear the Interval so as to hold on till the current method call is complete.
clearInterval(intervalVarUpload);
console.log("Updating table..");
var arrExplores = {
customArray: ["Yes", "Not", "Hello"]
};
Object.keys(arrExplores).forEach(function(key) {
if (arrExplores[key][2] != "Not") {
//remoteArrUpdate makes a json call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}
function remoteArrUpdate(id, key) {
setTimeout(function() {
//Consider as a ajax complete
uploadUpdate();
}, 2000)
}
<button id="uploadUpdate">Upload Update</button>
<button id="uploadStop">Upload Stop</button>

Firing a function every x seconds

I am currently using a keyup function to initiate my autosave.php file which auto saves information to a table. However, I am starting to find that the keyup seems to be inefficient due to fast typing and submitting long strings.
How can I have the ajax submit every x seconds, instead of each keyup after so many ms?
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
delay(function() {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
Solution
Use setInterval It is like setTimeout but repeats itself.
setInterval(function () {
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}, 1000);
Optimization
turn it on when the control has focus and turn it off when focus leaves. Also poll for the form data if it has updated then send the ajax request otherwise ignore it.
var saveToken;
var save = (function () {
var form;
return function () {
var form2 = $('#ajaxForm').serialize();
if (form !== form2) { // the form has updated
form = form2;
$.ajax({
type: "post",
url: "autosave.php",
data: form,
success: function(data) {
console.log('success!');
}
});
}
}
}());
$('.autosaveEdit').focus(function() {
saveToken = setInterval(save, 1000);
});
$('.autosaveEdit').focusout(function() {
clearInterval(saveToken);
save(); // one last time
});
I believe that what you are looking for is the window.setInterval function. It's used like this:
setInterval(function() { console.log('3 seconds later!'); }, 3000);
Use setInterval
function goSaveIt()
{
$.ajax({
type: "post",
url: "autosave.php",
data: $('#ajaxForm').serialize(),
success: function(data) {
console.log('success!');
}
});
}
setInterval(goSaveIt, 5000); // 5000 for every 5 seconds

simple ajax request with interval

I recently began learning Ajax and jQuery. So yesterday I started to programm a simple ajax request for a formular, that sends a select list value to a php script and reads something out of a database.
It works so far!
But the problem is, that when I click on the send button, it starts the request, 1 second later. I know that it has something to do with my interval. When I click on the send button, I start the request and every second it requests it also, so that I have the opportunity, to auto-refresh new income entries.
But I'd like to have that interval cycle every second, but the first time I press the button it should load immediately, not just 1 second later.
Here is my code:
http://jsbin.com/qitojawuva/1/edit
$(document).ready(function () {
var interval = 0;
$("#form1").submit(function () {
if (interval === 0) {
interval = setInterval(function () {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}, 1000);
}
return false;
});
});
Thanks!
I might be something like the following you're looking for.
$(document).ready(function () {
var isFirstTime = true;
function sendForm() {
var url = "tbladen.php";
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
}
});
}
$("#form1").submit(function () {
if (isFirstTime) {
sendForm();
isFirstTime = false;
} else {
setTimeout(function () {
sendForm();
}, 1000);
}
return false;
});
});
So, use setTimeout when the callback has finished as setInterval just keeps running whether or not your callback has finished.
$(function () {
$("#form1").submit(postData);
function postData() {
var url = "tbladen.php",
data = $("#form1").serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function (data) {
$("#tbladen").html(data);
setTimeout(postData, 1000);
}
});
return false;
}
});
Kind of related demo

Categories