how to get an event's completion time in jquery - javascript

hi i am using jquery .
i have a check box click event
jQuery('.btn-check-box').click(function () {
//code goes here .
});
the problem is the click event takes considerable time to complete.some times the browser gets stuck.
so i want to change the code inside the function and reduce the completion time .
now i want to get my current click event completion time .
then make changes to the code and again check the completion time .
so i can optimize my code according to the completion time .
is there any way to check an events completion time .
please help.
thanks in advance.

Pass event as argument.
var createdTime;
jQuery('.btn-check-box').click(function(e){
createdTime = e.timeStamp;
}).done(function(){ calculate time difference });
if you will use console.log(e) then it will show you that jQuery already passing timestamp when event is triggered.
so now you need to find a way when even is getting done so .done() jQuery method will help you.
In side .done() you can also get same e.timestamp and do some math on to get your desired out put in second, minutes or anything.

Like SrinivasR said, finish time - start time.
jQuery('.btn-check-box').click(function () {
var t0 = (new Date()).getTime();
//code goes here
console.log("Event took",(new Date()).getTime() - t0, "ms to complete.");
});

Try the following for your code
jQuery('.btn-check-box').click(function () {
var secondStart = new Date().getTime() / 1000;
// Your code goes here .
var secondEnd = new Date().getTime() / 1000;
var totalTime = secondEnd - secondStart;
console.log('Executing took' +totalTime +'seconds' )
});

Related

p5.js autoclicker calling

I have a simple question maybe, I was for days looking for solution and don't want to waste your time, but isn't work for me so I'm here now.
Im using P5JS, and I wanted to create auto click function.
There how I call an button in sketch.js file
var button1 = createButton("Generator");
button1.mousePressed(banana);
button1.id('autoclick');
Here you can see how I call in index.html
Im trying something like this:
<script type="text/javascript">
var iteration = true;
var time = new Date();
var delay = 5000; // 5 secondes
while(iteration) {
if(time.getTime() + 5000 < new Date().getTime()) {
iteration = false;
}
}
document.getElementByID('autoclick').click();
// noprotect
</script>
Maybe I complicate to much? any suggetions? thank you!
Your while loop is blocking, which means that while Javascript is running your while loop, it will not be able to execute any other code. You want to use setInterval() for your purposes.
For example,
setInterval(() => console.log("hello!"), 1000)

setTimeout() function being called twice in a row

I am writing a bot that sends alerts at variable intervals. I am using setTimeout() and I have an issue I can't seem to be able to figure out. The (simplified) code is:
//Original call to setTimeout():
timeout = setTimeout(issueAlarm, 2147483647); // highest possible interval setTimeout() will accept.
//In bot:
// dh is a priority queue that keeps timestamps sorted from smaller to larger as the user requests alerts.
//'mom' is a moment.js variable that holds the most recent request.
//This block of code checks the PQ and if what the user just entered is smaller than what is already stored, it updates the timeout.
//This seems to work fine
// First get input from user and store the desired time of first alert in 'mom'. Then:
var nextD = dh.peekNext();
if (nextD.timestamp >= mom.valueOf() ){
var now = new Date();
clearTimeout(timeout);
timeout = mom.valueOf() - now;
setTimeout(issueAlarm, timeout);
}
//issueAlarm function:
function issueAlarm() {
var next = dh.getNext(); // this pops the first alarm from the queue
// here goes some code that issues message. Then:
var peek = dh.peekNext(); // this looks at the next element in the queue without popping it
if (peek) {
var now = new Date();
timeout = peek.timestamp - now;
setTimeout(issueAlarm, timeout);
}
}
The example inputs are:
First input entered: Set an alert every 8 hours starting 5 minutes from now ("call Bob")
Second input entered: Set an alert every 8 hours starting 4 minutes from now ("call Jane")
In 4 minutes, i correctly get "call Jane" (this one gets set from the bot code)
One minute later, I correctly get "call Bob", but also i get "call Jane" (which should not happen until 8 hours later)
I printed all the timeout values and they seem correct. I also am printing the return of the setTimeout() function inside the issueAlarm() function.
Inside the first call: _idleTimeout: 59994 (this is correct, the next call is in one minute)
Inside the second call: _idleTimeout: 28739994 (this looks correct, it's approximately 8 hours, but still i get a third call right away)
Inside the third call: _idleTimeout: 28799991 (this timeout looks correct but this function call shouldn't have happened)
I'm using botFramework. My knowledge of JavaScript and node.js is far from extensive. I have printed out everything I could think of, but I can't figure out why that third call is being made right away.
This happens only if the first input entered requests an alert that starts later than the one entered in the second input. But I can't possibly understand why.
I thought you could have a problem with the Next function that returns you the data, take a look to my example. If your function is returning the next element as they were saved, you could not use that function, you need to build a function that return the first alarm to call. Hope it helps!
var dh = {};
dh.alarms = [{time: 1000, name:"Jane"},{time:5000, name:"Jane"},{time: 3000, name:"Bob"}];
dh.first = function(){
dh.alarms = dh.alarms.sort(function(a,b){return a.time - b.time});
next = dh.alarms.slice(0,1);
dh.alarms = dh.alarms.slice(1);
return next[0]
}
dh.next = function(){
next = dh.alarms.slice(0,1);
dh.alarms = dh.alarms.slice(1);
return next[0]
}
var timeout = setTimeout(executeAlarm, 2999999);
function start(){
var next = dh.first(); // dh.next(); I thought this is your problem!!
if(next && next.name){
clearInterval(timeout);
timeout = setTimeout(function(){executeAlarm(next)},next.time);
}
}
function executeAlarm(next){
if(!next || !next.name) clearInterval(timeout)
document.getElementById("alarms").innerHTML += "<span> Alarm for " + next.name + "</span>";
start();
}
document.addEventListener( "DOMContentLoaded", start, false );
<div id="alarms"></div>
(Posted on behalf of the OP).
The problem was here, in the bot code:
if (nextD.timestamp >= mom.valueOf() ){
var now = new Date();
clearTimeout(timeout);
timeout = mom.valueOf() - now;
setTimeout(issueAlarm, timeout);
}
I was clearing the timeout correctly the first time (when i cleared the original timeout of 2^31 - 1), but not afterwards. The issue is that the line in which i call setTimeout should be
timeout = setTimeout(issueAlarm, timeout);
So that the return is stored in a timeout object. I was making subsequent calls to clearTimeout() by passing a value, not an object, and therefore the timeout stored first (5 minutes, 'call Bob') was never cleared.
Thanks to #guest271314 and to #damianfabian for helping me get to the correct answer.

Why does setInterval not increment my clock properly in JavaScript?

I want to display the actual time in New York. I have a html div:
<div id="time"></div>
and also - I have a php script that returns the actual time:
<?php
date_default_timezone_set('UTC');
echo time();
?>
and it does it as a timestamp.
Now, I've created a js script:
var serverTime;
moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');
function fetchTimeFromServer() {
$.ajax({
type: 'GET',
url: 'generalTime.php',
complete: function(resp){
serverTime = resp.responseText;
function updateTimeBasedOnServer(timestamp) { // Take in input the timestamp
var calculatedTime = moment(timestamp).tz("America/New_York");
var dateString = calculatedTime.format('h:mm:ss A');
$('#time').html(dateString + ", ");
};
var timestamp = serverTime*1000;
updateTimeBasedOnServer(timestamp);
setInterval(function () {
timestamp += 1000; // Increment the timestamp at every call.
updateTimeBasedOnServer(timestamp);
}, 1000);
}
})
};
fetchTimeFromServer();
setInterval(function(){
fetchTimeFromServer();
}, 5000);
and the idea behind it is that I want to fetch the data from server, display it on my webpage, then increment it every second for five seconds and then fetch the time from the server again (to keep consistence with time on the server). And later on - continue with doing so, fetching the time, incrementing it for 5 seconds, fetching it again, etc.
It works... almost. After the webpage stays open for some time I can see the actual time, but it 'blinks', and I can see that it shows different times - it's hard to explain, but it looks like there is some time already in that div and new time tries to overlay it for each second. Seems like the previous time (content of this div) is not removed... I don't know how to create a jsfiddle with a call to remote server to fetch time from php, so I only have this information pasted above :(
What might be the problem here?
Since javascript is single threaded, setInterval may not acutally run your function after the delay. It adds the function to the stack to be run as soon as the processor is ready for it. If the processor has other events in the stack, it will take longer than the interval period to run. Multiple intervals or timeouts are all adding calls to the same stack for processing. To address this, you could use HTML5 web workers or try using setTimeout recursively.
Here is a good read on web workers: https://msdn.microsoft.com/en-us/hh549259.aspx

Javascript executing button click on page event

I'm new to javascript, and I'm trying to see if what I want to do is possible. I want to take a current webpage that I have open in my browser, and execute new javascript. There is a timer on this page, and when it increases to a particular time, I want it to execute a button click.
This would be the time that is changing and that I want to add into a if statement:
07:34:04
Will this changing time raise an event that would cause a javascript to run? I want something along the lines of:
if time = 7:35:00 then click button.
Thanks for your help!
I'll like to make a contribution..
I don't know much about the javascript time format, but I'll post back if I can look it up.
Any way you can use a function such as this:
var waiter;
function waitForTimer(extime, fn)
{
//Here, fn is the function to be executed..
//While extime is the time at which the function is to be executed..
waiter = setInterval(function(fn,extime){
//this function will check every one second..
if( extime == time )
{
fn();
clearInterval(waiter);
}
else
log("waiting for " + time);
}, 1000);
}
I hope this helps.

jQuery event only every time interval

$(document).ready(function() {
$('#domain').change(function() {
//
});
});
The code inside the change function will basically send ajax request to run a PHP script. The #domain is a text input field. So basically what I want to do is to send ajax requests as user types in some text inside the text field (for example search suggestions).
However, I would like to set a time interval in order to lessen the load of PHP server. Because if jQuery sends AJAX request every time user adds another letter to the text field it would consume lots of bandwidth.
So I would like to set let's say 2 seconds as an interval. The AJAX request will be fired every time the user types a letter but with maximum frequency of 2 seconds.
How can I do that?
$(function() {
var timer = 0;
$("#domain").change(function() {
clearTimeout(timer);
timer = setTimeout(function(){
// Do stuff here
}, 2000);
});
});
$(document).ready(function() {
var ajaxQueue;
$('#domain').change(function() {
if(!ajaxQueue) {
ajaxQueue = setTimeout(function() {
/* your stuff */
ajaxQueue = null;
}, 2000);
}
});
});
What you really want to do is check how long since the last change event so you keep track of the number of milliseconds between events rather than make a call every 2 seconds.
$(document).ready(function() {
var lastreq = 0; //0 means there were never any requests sent
$('#domain').change(function() {
var d = new Date();
var currenttime = d.getTime(); //get the time of this change event
var interval = currenttime - lastreq; //how many milliseconds since the last request
if(interval >= 2000){ //more than 2 seconds
lastreq = currenttime; //set lastreq for next change event
//perform AJAX call
}
});
});
Off the top of my head without trying this in a browser. Something like this:
$('#domain').change(function() {
if (!this.sendToServer) { // some expando property I made up
var that = this;
this.sendToServer = setTimeout(function(that) {
// use "that" as a reference to your element that fired the onchange.
// Do your AJAX call here
that.sendToServer = undefined;
}, yourTimeoutTimeInMillis)
}
else {
clearTimeout(this.sendToServer);
}
});
two variables, charBuffer, sendFlag
Use a setTimeout to have a function be called every two seconds.
This function checks if the buffer has stuff in it.
If it does, it sends/empties the stuff and clears the sent flag (to false).
and It should also clear the timeout, and set it again
else it sets the flag (to true).
Everytime the user hits a key, store it in the buffer.
if the sent flag is clear (it's false), do nothing.
else (it's true) send/empty the stuff currently in the buffer and clear the flag (to false),
and It should also clear the timeout, and set it again
This will make it so that the first time you press a key, it is sent, and a minimum of 2 seconds must pass before it can send again.
Could use some tweaking, but i use this setup to do something similar.
I am coming across this problem more and more (the more i do UI ajax stuff) so i packaged this up into a plugin available here

Categories

Resources