Set default "reaction time" when interval is not broken jquery - javascript

I'm stuck with this one and hope that anyone can help me.
The script picks a word and records the elapsed time (reaction time) between word appearance and keypress. My idea was to have one function that picks the word, set it as interval, and have this interval broken by keypress. The attributes "stim" and "type" are for further use and I got problems if I had them picked more than once.
Here it is on fiddle: Fiddle of my problem
It does not, however, work quite correct. The default reaction time (2000ms), should only be recorded when there is no keypress. But as it is now, its recorded each time.
Js code:
var teststim = [{
stim: "A",
type: "letter"
}, {
stim: "B",
type: "letter"
}, {
stim: "1",
type: "integer"
}, {
stim: "2",
type: "integer"
}];
var RT = [];
var Type = [];
var Stim = [];
var displayword = function () {
stuff = teststim[Math.floor((Math.random() * teststim.length))];
$("#present").fadeOut(1000, function () {
$("#present").text(stuff.stim).fadeIn();
t1 = (new Date()).getTime();
});
reac = 2000;
};
timing = setInterval(displayword, 2000);
$(document).keypress(function (e) {
clearInterval(timing);
var t2 = (new Date()).getTime();
reac = t2 - t1;
t1 = t2;
timing = setInterval(displayword, 2000);
});

If I understood your question correctly, your mistake is here:
reac = 2000; RT.push(reac); $("#RT").val(RT);
You push and show reaction time as soon as you show word to type.
Here is your fiddle fixed.
Key is to first show the word and then start counting and not do it concurrently.
By the way there is still a little problem with reseting t1 in wrong place, so if you hit the keypress before fadeOut, but after default reaction time has fired, you'll get result like "2200".
You can fix it by, for example, putting it out of fadeOut: fiddle
To make it also change every time you press a key you can modify it like that: fiddle

Related

Javascript stop setInterval

if (document.case.display.value.length >16 && document.case.display.value.length < 21) {
Notiflix.Notify.Info('Because you have a lot of charatchers font size is smaller');
document.getElementById("display").style.fontWeight = "550";
document.getElementById("display").style.fontSize = "2em";
} else if (document.case.display.value.length > 20) {
var str = document.case.display.value.length
Notiflix.Notify.Warning('Max characters you can see is 25 ');
Notiflix.Notify.Failure('Number of your characters' + str);
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "1.5em";
}
else {
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "2.5em";
}}
window.setInterval(function(){
testLength();
}, 100);
Notiflix is a JavaScript library for notification.
I have a display who font go down if have so much characters and i set time every 0.1 second he check number of characters. If number is higher than 16 he put a notification.
But he put every 0.1 second notification i want only one time/s. Do you have idea who can "block " this line of code for 10 second and after that read this without moving settimer down.
Sorry about bad English.
Any information will help me
You can try storing your setInterval() in a variable and calling it only when required. Else, you can stop that using that variable name.
let myInterval;
function start(){
myInterval = window.setInterval(function(){
testLength();
}, 100);
}
function stop(){
clearInterval(myInterval);
}
P.S: I would also like to advice on using onChange eventListener for checking test length rather than setInterval.
Update: Alternate method
You can also try removing setInterval thing and adding something like this:
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit")
console.log("numbers", numbers);
numbers.forEach(el => el.addEventListener('click', testLength))
});

Detect time lapse between two key press in Javascript

I am learning javascript and at the same time trying to create a simple script that allows you to type a foreign language on a web browser with your keyboard.
So, when you type a for example, there is a single letter mapped to a, so a single character Դ would appear, however to make a character like 厄 appear, you have to type twice, since this language has more characters than the English alphabet.
So, the problem is with that last character. Normally, I should have to type g and h consecutively in the span of one second to produce the 厄 letter, but I have problems waiting to check if within two characters have been typed within one second of eachother inorder to show that letter.
So, I don't think time interval functions are the way to go about this, but I can't see any other method also.
cautions: check key whether up in keydown() & notify keydown the key is upped in keypress();
var start = null;
$('#in').keydown(function (e) {
if (!start) {//checking is a new user input
start = $.now();
}
}).keyup(function (e) {
var timeElapsed = $.now() - start;
start = null;//start the next timing tracking
console.log(['time elapsed:', timeElapsed, 'ms'].join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<h2>please input some letter to test</h2>
<input id="in"/>
</label>
another answer about your question,perhaps this is your truly answer.
function duration(timestamps) {
var last = timestamps.pop();
var durations = [];
while (timestamps.length) {
durations.push(last - (last = timestamps.pop()));
}
return durations.reverse();
}
function display(mills) {
if (mills > 1000)
return (mills / 1000) + ' s';
return mills + ' ms';
}
var durations = [];
$('#in').keydown(function (e) {
durations.push($.now());
}).keyup(function (e) {
var current = durations;
current.push($.now());
durations = [];
var timeElapsed = current[current.length - 1] - current[0];
console.log([
['time elapsed:', display(timeElapsed)].join(' '),
['keys duration:', duration(current).map(display)].join(' ')
].join(' --- '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<h2>Please input something to test!</h2>
<input id="in"/>
</label>
Below is the sample code to measure the elapsed time between any 2 events.
I added setTimeout just to give you an example.
var startTime = Date.now();
setTimeout(function(){
var elapsedTime = Date.now() - startTime;
console.log('elapsedTime ='+elapsedTime);
}, 100);
Like Alex mentioned, for every press, simply store new Date().getTime(); in a variable, which will get you the latest UTC time. UTC time is given in milliseconds, so on the next key-press, just see if the current time and the stored time differ by 1000!

Javascript: Handling timers with multiple lengths of delay?

Essentially what I'm trying to get this to do is display a list of words given by #words on a textarea #display.
Each word is displayed one at a time, delayed by an amount of time designated by getTextSpeed which retrieves speed options chosen by the user.
For example, if the user selects 350 WPM as their desired speed for delay, then each word will have a delay of 117 ms. If they decide to change it to 400 WPM, the delay should decrease in real time dynamically to a delay of 150 ms without having to restart the display animation.
Additionally, if the word contains a character of punctuation, then the delay after the word is displayed should be doubled (ex: 117 ms to 234 ms) and the character should be removed. If there's multiple characters of punctuation, just one should be removed (ex: "..." --> "..")
Below are the relevant methods and my attempt at implementing this behavior.
If you need the rest of the code (for testing purposes?), please see these pastebin links: HTML, Javascript, CSS.
I haven't encountered any errors in the console, but the actual reflected behavior isn't what I want for sure.
There's a lag period at the beginning of starting the animation, which seems to vary based on the length of the input text, and the delay between each word is far, far longer than it should be. Additionally, the punctuation doesn't appear to remove correctly. EDIT #1: I just double-checked the string.remove syntax and you're supposed to put the actual String, not actually call the method from the String superclass.
Please let me know if you need any other information.
var timer;
function start() {
var text = document.getElementById("words").value;
var list = text.split(/\s+/);
runDisplay(list, "display");
}
function runDisplay(data, id) {
var reader = document.getElementById(id);
var index = 0;
var punctDelay = 0;
if (timer) {
clearInterval(timer);
}
if (data.length) {
timer = setInterval(function() {
var punctuation = [".", ",", ":", ";", "!", "?"];
var word = data[index++];
for (var j = 0; j < punctuation.length; j++) {
if (!(word.indexOf(punctuation[j]) === -1)) {
// word = String.replace(punctuation[j], '');
word = word.replace(punctuation[j], ''); // see edit #1
punctDelay = getTextSpeed();
}
}
reader.innerHTML = word;
index = index % data.length;
}, getTextSpeed() + punctDelay); // change speed dynamically in real time
}
}
function stop() {
var display = document.getElementById("display");
clearInterval(timer);
timer = null;
display.innerHTML = "";
}
function getTextSpeed() {
var speeds = document.getElementById("speed");
return speeds.options[speed.selectedIndex].value;
}

JavaScript Timer countdown to logout

I'm trying to make a countdown timer in JS that will change the value of a field every one minute (in the begining there is 20, and then change it to 19,18,17 etc), but it's not working correctly. It's changing value not every 60sec but I have a feel that it works random (sometimes it change value first time after 15 sec, another time it's 53). Any idea what I'm doing wrong? Here is the code:
function getTimeNow(){
var Time = new Date;
return Time.getHours()*60*60+Time.getMinutes()*60 + Time.getSeconds();
}
var start = getTimeNow();
var start_point = start%60;
var target = start+60*20;
function TimeOut(){
if((getTimeNow()-start)%60 == start_point && target>getTimeNow()){
var temp = jQuery('.Timer').html();
temp-=1;
jQuery('.Timer').html(temp);
}
setTimeout(TimeOut,1000);
}
You cannot count on the exact moment a timer function will be called. You need to change your logic to something more resilient to time shifts...
setInterval(function(){count.innerText = count.innerText - 1;},
60*1000);
this is also a lot shorter...

How to make a real Javascript timer

I'm looking for a way to manipulate animation without using libraries
and as usual I make a setTimeout in another setTimout in order to smooth the UI
but I want to make a more accurate function to do it, so if I want to make a 50ms-per-piece
animation, and I type:
............
sum=0,
copy=(new Date()).getMilliseconds()
function change(){
var curTime=(new Date()).getMilliseconds(),
diff=(1000+(curTime-copy))%1000 //caculate the time between each setTimeout
console.log("diff time spam: ",diff)
sum+=diff
copy=curTime
var cur=parseInt(p.style.width)
if (sum<47){//ignore small error
//if time sum is less than 47,since we want a 50ms-per animation
// we wait to count the sum to more than the number
console.log("still wating: ",sum)
}
else{
//here the sum is bigger what we want,so make the UI change
console.log("------------runing: ",sum)
sum=0 //reset the sum to caculate the next diff
if(cur < 100)
{
p.style.width=++cur+"px"
}
else{
clearInterval(temp)
}
}
}
var temp=setInterval(change,10)
I don't know the core thought of my code is right,anyone get some ideas about how to make a more accurate timer in most browser?
Set the JsFiddle url:
http://jsfiddle.net/lanston/Vzdau/1/
Looks too complicated to me, use setInterval and one start date, like:
var start = +new Date();
var frame = -1;
var timer = setInterval(checkIfNewFrame, 20);
function checkIfNewFrame () {
var diff = +new Date() - start;
var f = Math.floor(diff / 50);
if (f > frame) {
// use one of these, depending on whether skip or animate lost frames
++frame; // in case you do not skip
frame = f; // in case you do skip
moveAnimation();
}
}
function moveAnimation () {
... do whatever you want, there is new frame, clear timer past last one
}

Categories