How can I create a Node.JS accurate timer? It should look like a kitchen timer or a stopwatch.
And I need accuracy, as much as possible. The application will promote some kind of "clicks war". I need to store every (concurrent) user's click, noting seconds and milliseconds (to tie the game).
How can I do it? Are there some code sample?
Thanks in advance.
Well You should have a look at microtime module, which gives you the time as accurate as microseconds. You can even measure CPU tick time with it!
As of the code well you can do something like this (Storing the time in objects and then accessing them with the user id, advantage would be no duplicate of the same user and faster access to one, if the user name is known):
var microtime = require('microtime');
, clicks = {};
click(function(user){ // An event listener for received clicks
clicks[user] = microtime.now();
});
or (pushing all in an array, advantage would be that it can be sorted, and easily all of them be iterated)
var microtime = require('microtime');
, clicks = [];
click(function(user){ // An event listener for received clicks
clicks.push({
user : user,
time : microtime.now()
});
});
As of node v0.8.0 you can use process.hrtime() which will return an array both containing a relative seconds and nanoseconds to past.
Related
I'm creating an input field where some data should be fetched (by AJAX) and displayed every time the user enters data into that field. However, if the user types several characters, say he types "test" to get all records who contain the string "test", it would not be necessary to do 4 queries after every character pressed, but one query after he stopped typing. I can think of several solutions with a global variable where I check if the same event has been fired again, but is there a really elegant way to do this? Maybe check if there is something in the keyboard buffer and only proceed if it is empty? Or is there an event that is only fired once the keyboard buffer is empty and all characters are in the input field?
The elegant way is to use a timeout, and to keep clearing the previous timeout with each key press
var tID;
function keyUp (e) {
if (tID) clearTimeout(tID);
tID = setTimeout(function() {
... // make web call
}, 2000);
}
This will ensure that the web call is only called after the last key is pressed (you may want to adjust the timeout value)
There are ways to achieve this that I can think of:
Use timeout, from the last keyup event. This is not always the best and not that precise with users that have low typing speed.
Use space character do regconize if the user has finished typing a word. Based on changes in length and total word count, you can decide if you would want to send AJAX or not.
Depends on the type of input you are working with, you may choose the most suitable method for you. The first one is somewhat quite rigid. The second method requires user to press space every time he finishs typing. A little bit of both could be a sweet spot perhaps. In modern day, I don't think sending request every keyup will cause huge performance effect though.
I have seen a lot of duplicates on this subject, but I don't see how to actually get done what needs to be done.
I have a list of URLs in one sheet tab and an IMPORTXML() function in another. I'm writing a script to copy each URL to the second tab then perform an action based on the output of the IMPORTXML(). For this to work, I need a slight delay in the script to ensure the IMPORTXML() has calculated before continuing. setTimeout() doesn't seem appropriate here, because I need the other parameters of the script (which row it's checking, etc) to be calculated based on outputs. Help!
function test(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var list = sh.getSheetByName("Dec 2018").getRange(row,3,sh.getSheetByName("Dec 2018").getLastRow()-row).getValues();
var check = sh.getSheetByName("Check");
for(var row = 2;row<500;row++){
check.getRange(1,1).setValue(list[row-2][0]);
//wait right here
//other code to run based on the output of the =IMPORTXML() formula on the Check sheet
}
}
To insert a slight delay use Utilities.sleep(milliseconds) with a milliseconds value big enough to wait the slowest recalculation time (I think that it's 30000 ms for a single formula because it's the execution time limit for custom functions). If you want to optimize this time, maybe you will want to use a technique like exponential back-off
Note: The Window object isn't available on Google Apps Script server side code execution, so setTimeout() can't be used.
I want to implement localStorage for one of my values in my Achievements class. So basically what this class does is take player data from backend database and if a player clears certain tasks an achievement gets unlocked. For now I have just 1 achievement defined as follows
Achievements:{ 1:{name:'First_Achievement',status:1} },
The status field acts like a flag for my achievements. If status is 1 then achievement is still locked and if it goes 0 the achievement gets unlocked.
This is a skeleton code for when my achievement gets unlocked. This block of code is checked in my game every 10 seconds to see if a certain task is cleared to unlock an achievement
checkAchievements:function(){
this.probsSolved = this.getTeamProbSolved();
if( this.Achievements[1].status == 1 && this.probsSolved.length >=3)
this.triggerAchievement(1); // spawns achievement 1 on screen
this.Achievements[1].status = 0;
},
So this works fine when I run the game. The "this.Achievements[1].status" is set to 0 until I start my game again the next time. It sets the "this.Achievements[1].status" back to 1 and the if loop runs again as status is set back to 1 which I don't want because its obvious I want my achievement to be spawned or displayed just once and not every time I run the game.
So how do go about an implement localStorage here? I suppose I need to store my "Achievements.status" field in the localStorage so that the if loop runs just once and not everytime. Or is there any other way I can implement this?
I tried the following
localStorage.setItem(this.Achievements[1].status,0);
but it does not work
any help would be appreciated! Thanks!
First, I'd recommend reading the documentation on localStorage at MDN - https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage. Next, let's look at your call:
localStorage.setItem(this.Achievements[1].status,0);
This says: I want you to store a value, 0, and retrieve it by the key that is the value of this.achievements[1].status.
That seems to be booleans for you. So you basically did:
localStorage.setItem(true, 0)
The localStorage API expects a string for the keyname, so it will get the string value of true which is, true. So it probably did work for you, but you used a key that probably isn't what you want. You need to think of a key name scheme that makes sense for you.
I want to measure UI interaction time like following.
Time between Menu selected and showing result.
Time between User typing & showing letters in UI
I think many people suggest me to measure the time between function call & result, but I want to know another way to get the time though UI changes.
Is it possible to check the time for UI changes ?
The tool what I'm developing is made by Javascript and run on Browser.
Here is my answer:
"Javascript is single threaded".
So,what does this means:
Javascript runs code sequentially.It is not possible to run two
different pieces of Javascript code at the same time because it does
not support multithreading.
Execution of javascript code is line by line.So execution of multiple lines at same time is not possible(it will be very small though)
A simple solution:
check_my_time_first() ;//these will be functions returning the epoch time
check_my_time_after();
You just need console.log,flag variables and epoch time.
Firstly,the difference will be ultra small.
var milliseconds_before = (new Date).getTime();//use this code when user clicks
var milliseconds_after = (new Date).getTime();//use this when result appears.
Make use of flag variables to know when some execution has been completed.
Another example:
var execution_over=false;
function doSomething(){
console.log("start_time"+milliseconds_before)
//some code to be executed;
execution_over=true
if(execution_over==true){
console.log("time="+milliseconds_after)
}
}
Difference:
var diff=milliseconds_before - milliseconds_after;
Place this code smartly and you will see the difference in time.
The important thing is to understand the fundamentals.I hope my answer helped.
I want to develop a simple app to measure dwell time and flight time (see http://www.techrepublic.com/article/reduce-multi-factor-authentication-costs-with-behavioral-biometrics/6150761) in a text area / box. how can I use keypress() or keydown() up() methods to record these events?
I don't understand why this would not be worth it. Just because Javascript can be modified on the client side does not mean an attacker could reproduce an actual user's typing patterns.
Doing this on the client side has the added benefit of keeping the user's data private (e.g. you're not actually collecting user's keystrokes, but only information related to their typing patterns).
I'm sure there are still privacy concerns, but this is a very interesting authentication (or auditing/detection) control.
See an example here: http://jsfiddle.net/VDMPt/ source
But as Andrea said, is not worth it since Javascript is client side
var xTriggered = 0;
$('#target').keyup(function(event) {
if (event.keyCode == '13') {
event.preventDefault();
}
xTriggered++;
var msg = 'Handler for .keyup() called ' + xTriggered + ' time(s).';
$.print(msg, 'html');
$.print(event);
});
$('#other').click(function() {
$('#target').keyup();
});
I believe this approach would not be fruitful in a real-world environment, because whatever processing you do in Javascript is, in line of principle, easily modifiable by the user, by using a simple javascript debugger or programs like Firebug.
That said, you could measure the two metrics in this way:
dwell time = time between keydown() and keyup(). In your keydown() method save the current time and in the keyup() compute the twell time as the difference between the current time and the keydown() time.
flight time: from the figure of the article you linked I can't easily understand how it is defined, but I would compute it as the difference between when you left the last key (keyup()) and when you start pressing the next key (keydown()). So in keyup() save a time, for instance last_key_time, and in keydown() compute the flight time as current_time - last_key_time