I want to check if Enter key was pressed twice within 5 secs and perform some action.
How can I check if the key was pressed once or twice within a given time and perform different actions.
Here is my code:
<h1 id="log">0</h1>
<br/>
<span id="enteredTime">0</span>
<script>
$(document).keypress(function(e) {
if(e.which == 13){
var element = $("#log");
var timeDifference = 0;
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
//Check if enter was pressed earlier
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
//Check if enter was pressed only once within 5 secs or more
if(){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
});
</script>
http://jsfiddle.net/Rjr4g/
Thanks!
something like
var start=0;
$(document).keyup(function(e) {
if(e.keyCode == 13) {
elapsed = new Date().getTime();
if(elapsed-start<=5000){
//do something;
}
else{
//do something else;
}
start=elapsed;
}
});
Try a timer based solution like
var flag = false,
timer;
$(document).keypress(function (e) {
var element = $("#log");
var timeDifference = 0;
if (e.which == 13) {
if (flag) {
console.log('second');
clearTimeout(timer);
flag = false;
} else {
console.log('first');
flag = true;
timer = setTimeout(function () {
flag = false;
console.log('timeout')
}, 5000);
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
Demo: Fiddle
Bacon.js seems like a good tool to express this.
$(document).asEventStream('keypress')
.filter(function (x) {
return x.keyCode == 13;
})
.map(function () {
return new Date().getTime();
})
.slidingWindow(2, 1)
.map(function (x) {
return (x.length == 1 || x[1] - x[0] > 5000) ? 1 : 2;
})
.onValue(function (x) {
$("#log").text(x == 1 ? "Once" : "Twice in less than 5 secs");
});
(fiddle)
here is my solutions, please check it if match your idea :)
(function($){
var element = $("#log");
var timeDifference = 0;
var count = 0;
$(document).keypress(function(e) {
if(e.which === 13){
//do what you want when enterpress 1st time
/*blah blah */
//after done 1st click
count++;
if(count === 2) {
//do what you want when enterpress 2nd time in 5 seconds
/* blah blah */
//after done
clearTimeout(watcher);
count = 0;
return;
}
//setTimeout to reset count if more than 5 seconds.
var watcher = setTimeout( function() {
count = 0;
},5000);
}
});
}(jQuery)
Check your Updated Fiddle
var count = 0;
$(document).keypress(function(e) {
var element = $("#log");
var timeDifference = 0;
if(e.which == 13){
count++;
console.log('enter pressed'+count);
if(count == 1){
startTimer();
}
else{
checkCount();
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
function startTimer(){
setTimeout(checkCount,5000);
}
function checkCount(){
if(count == 1){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
startTimer() starts counting on first enter press. And checkCount() contains your condition after 5secs.
setTimeout() lets you attach an event which occurs after a specific timespan.
Related
I created a stopwatch using JavaScript, and I'm trying to start/stop the timer by space key, but it doesn't stop but always became more faster.
'''
var timer_start = "S";
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
time = setInterval(timer, 10);
if (timer_start == "S") {
timer_start = "F";
} else if (timer_start == "F") {
clearInterval(time);
timer_start = "S";
}
}
};
,,,
Once the spacebar is pressed, you are starting the timer again regardless of the current value of timer_start. You need to move this to be inside the if statement. I'd also recommend using a Boolean instead of the string "S" and "F".
Here is my proposed rewrite of your code:
var timer_start = true;
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
if (timer_start) {
time = setInterval(timer, 10);
timer_start = false;
} else {
clearInterval(time);
timer_start = true;
}
}
};
You could also shorten it a bit by doing this if you wanted
var timer_start = true;
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
if (timer_start) {
time = setInterval(timer, 10);
} else {
clearInterval(time);
}
timer_start = !timer_start
}
};
You set the interval regardless of the timer_start state, so you keep piling up new intervals and remove only half of them. You should set the interval only in the timer_start == "S" branch.
I'm making a shot clock for my school's basketball team. A shot clock is a timer that counts down from 24 seconds. I have the skeleton for the timer right now, but I need to have particular key bindings. The key bindings should allow me to rest, pause, and play the timer.
var count=24;
var counter=setInterval(timer, 1000);
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs";
}
I'm not sure what you meant by "rest" the timer, I interpret this as "pause", so:
Space = Pause / Play.
R = Reset.
var
count=24,
counter = setInterval(timer, 1000),
running = true;
function timer() {
count -= 1;
if (count <= 0) {
clearInterval(counter);
}
document.getElementById("timer").innerHTML = count + " secs";
}
window.addEventListener("keydown", function(e) {
switch(e.keyCode) {
case 32: // PLAY
running ? clearInterval(counter) : counter = setInterval(timer, 1000);
running = !running;
break;
case 82: // RESET
clearInterval(counter);
document.getElementById("timer").innerHTML = 24 + " secs";
count = 24;
running = false;
}
});
<div id="timer">24 secs</div>
I am not able to comment yet, but I recommend checking out this post Binding arrow keys in JS/jQuery
The linked post explains how to bind arrow keys using js/jquery. Using http://keycode.info/ you can find out the keycodes of your desired keys and replace the current values then continue to build your code from there.
Here is my code sample: http://codepen.io/anon/pen/vLvWJM
$(document).ready(function() {
var $timer = $('#timer');
var $timerStatus = $('#timerStatus');
var timerValue = 24;
var intervalId = null;
var timerStatus = 'stopped';
if(!$timer.length) {
throw 'This timer is missing a <div> element.';
}
$(document).keydown(function(k) {
if(k.which == 80) {
if(timerStatus === 'playing') {
clearInterval(intervalId);
timerStatus = 'stopped';
updateTimerStatus();
return;
}
intervalId = setInterval(function() {
playTimer();
timerStatus = 'playing';
updateTimerStatus();
}, 1000);
} else if(k.which == 82) {
clearInterval(intervalId);
resetTimer();
updateText();
timerStatus = 'stopped';
updateTimerStatus();
}
});
function playTimer() {
if(timerValue > 0) {
timerValue--;
updateText();
}
}
function resetTimer() {
timerValue = 24;
}
function updateText() {
$timer.html(timerValue);
}
function updateTimerStatus() {
$timerStatus.html(timerStatus);
}
});
<div id="timerStatus">stopped</div>
<div id="timer">24</div>
function testworking(n){
if(n == 1)
testuser();
else
testconfig();
}
setInterval(function(){testworking(n)}, 1000);
How do I make that function testuser(); could not start earlier than 10 seconds after the previous launch?
P.S.:
an approximate algorithm:
if(n == 1){
if (first run function `testuser()` ||
time after previous run `testuser();` == 10 seound){
testuser();
}
}
Set a flag using a timer:
var is_waiting = false;
function testuser() {
if (!is_waiting) {
//do your stuff here
} else {
alert('You must wait ten seconds before doing this again');
}
is_waiting = true;
setTimeout(function() {is_waiting = false}, 10000);
}
You can do it like this
var i = 0;
function testworking(i){
if(i < 10) {
console.log(i);
} else {
console.log('Here is 10 second');
}
}
setInterval(function(){
i = (i == 10) ? 0 : i;
i++;
testworking(i);
}, 1000);
It's not entirely clear what you're looking for, but here's something that might give you an idea.
var n = 1;
var testUserInterval;
function testworking(n) {
if (n == 1)
testuser();
else
testconfig();
}
function testuser() {
var cnt = 0;
if (testUserInterval == null) {
testUserInterval = setInterval(function() {
document.getElementById("testusercnt").innerHTML = cnt;
cnt += 1;
if (cnt == 10) {
clearInterval(testUserInterval);
testUserInterval = null;
//DO SOMETHING ???
testuser();
}
}, 1000);
}
}
function testconfig() {
document.getElementById("testconfig").innerHTML = n;
}
setInterval(function() {
testworking(n++)
}, 1000);
testuser cnt:<span id="testusercnt"> </span>
<br/>testconfig n: <span id="testconfig"> </span>
I have my function that records the reaction time from the display of the stimulus (word or picture) until the keypress.
But if there is no key pressed, the reaction time will be NaN, yet I'd like it to run through until the next stimulus appears (here after 1000ms), so that the reaction even if no key is pressed is then equal to 1000ms:
How could I record the milliseconds until 1000ms if there is no keypress event?
var t1;
var i = 0;
$(function(){
var timeout = 0;
function showNext() {
t1 = (new Date()).getTime();
if(Math.random() < 0.5) {
var new_word = stim[Math.floor((Math.random()*stim.length)+1)].name;
$("#abc").text(new_word);
} else {
var new_img = stim[Math.floor((Math.random()*stim.length)+1)].path;
$("#abc").empty();
var prox_img = $('<img id="abcimg" height="300px" width="300px">');
prox_img.attr('src', new_img);
prox_img.appendTo('#abc');
}
timeout = setTimeout(function(){showNext()}, 1000);
}
$(document).keypress(function(e){
if ($(e.target).is('input, textarea') || i > 10) {
return;
};
i++;
clearTimeout(timeout);
if (e.which === 97 || e.which === 108 || e.which === 32) {
setTimeout(function(){showNext();}, 100);
var t2 = (new Date()).getTime();
var reac_time = t2-t1;
$("#time").text(reac_time);
}
});
});
At the start of showNext(), just check if the displayed time is NaN, and set it to 1000.
function showNext() {
if( isNaN($("#time").text()) ){
$("#time").text("1000");
}
//... your other code
}
See w3Schools isNaN()
I would like this function to begin quicker once it ends. Thanks.
demo: http://jsfiddle.net/RuX5d/5/
Here is an actual timing I am currently using: http://jsfiddle.net/RuX5d/51/
$(document).ready(function() {
var i = 1, dir = 1, curFx = 'fadeIn';
var interval = setInterval(function () {
if (i == 6 && $('#slide1').is(':visible')) {
$('#slide1').fadeOut(2000);
return;
}
$('#slide'+ i)[curFx](500);
i = i + 1*dir;
if (i == 10 || i == -1) {
dir = (dir == 1)?-1:1;
curFx = (curFx == 'fadeIn')?'fadeOut':'fadeIn';
}
}, 1000);
});
Change the 500 at the end. It is the number of milliseconds between each executions of the script. Here's a demo: http://jsfiddle.net/RuX5d/49/