Stop jquery event - javascript

I want if I call my second if else work then first one should stop. But that also keep running. If first one running second should stop.
if(e.keyCode == 39) {
setInterval(function(){
//
}, 10);
} else if(e.keyCode == 37) {
setInterval(function(){
//
}, 10);
}

setInterval() returns the ID of the set timer, that can be used to stop it.
Something like this should work:
var intervalId1, intervalId2;
if(e.keyCode == 39) {
intervalId1 = setInterval(function() { ... }, 10);
if (intervalId2) {
clearInterval(intervalId2);
}
} else if(e.keyCode == 39) {
intervalId2 = setInterval(function() { ... }, 10);
if (intervalId1) {
clearInterval(intervalId1);
}
}

You need to use a variable which is in a shared scope
//in a shared scope, probably outside teh function where this code is placed
var interval;
if (e.keyCode == 39) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(function () {
//
interval = undefined;
}, 10);
} else if (e.keyCode == 37) {
if (interval) {
clearInterval(interval);
}
interval = setInterval(function () {
//
interval = undefined;
}, 10);
}

setInterval returns a handle which you can use to stop/clear the interval.
It is also important that you store this handle outside the function itself, or else it will be cleared next time the function runs.
Since you only care about one interval to run, you also only need to store one handle.
//define globally outside your function
var interval = null;
//your function starts here
interval && clearInterval(interval); // (same as if(interval){clearInterval(interval);})
if(e.keyCode == 39) {
interval = setInterval(function(){
//
}, 10);
} else if(e.keyCode == 37) {
interval = setInterval(function(){
//
}, 10);
}

Using one variable interval to store the return id of setInterval and whenever call to function clear that interval you will get what you need.
var interval;
$("#text_box").keydown(function(e){
e.preventDefault();
if(e.keyCode == 39){
clearInterval(interval);
interval=setInterval(sample1,1000);
}
else if(e.keyCode == 37){
clearInterval(interval);
interval=setInterval(sample2,1000);
}
});
function sample1(){
console.log("1");
}
function sample2(){
console.log("2");
}

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

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.

clearIntervall don't stop scrolling set with timer

I'm a js newbie but from what I read, using clearInterval with id returned previously by setInterval should reset the timer.
On a pedal push I receive a midi event with a positive value and then same event with a zero value on pedal release.
Using the code below, I can see my page turning red on release but the page keeps scrolling. Any idea why ?
function handleMIDIMessage(event) {
var scroll_id;
if (event.data.length === 3) {
if (event.data[0] == 176 && event.data[1] === 67) {
if (event.data[2] > 0) {
scroll_id = setInterval(function() {
window.scrollBy({
top: 50,
behaviour: "smooth"
});
}, 1000);
document.body.style.background = 'green';
} else {
document.body.style.background = 'red';
clearInterval(scroll_id);
}
}
}
}
You need to declare the interval outside so you do not keep creating a new variable and losing the id. You should probably also check to make sure you are not creating more than one interval.
//declare it so it is not overwritten
var scroll_id;
function handleMIDIMessage(event) {
if (event.data.length === 3) {
if (event.data[0] == 176 && event.data[1] === 67) {
if (event.data[2] > 0) {
// if we were defined before, cancel the last one
if (scroll_id) window.clearInterval(scroll_id);
scroll_id = setInterval(function() {
window.scrollBy({
top: 50,
behaviour: "smooth"
});
}, 1000);
document.body.style.background = 'green';
} else {
document.body.style.background = 'red';
clearInterval(scroll_id);
}
}
}
}

Javascript How do i check every 5 seconds if a specific key was clicked?

In this case, how do i check every 5 seconds if the right arrow button was clicked? Here what i've tried. It only works once and never checks again. What am i doing wrong?
setInterval(KeyPressed, 5000);
window.onkeydown = KeyPressed;
function KeyPressed(k) {
if (k.keyCode == 39) {
alert("Right Arrow");
}
}
Perhaps this?
Check if the last key that was clicked is the arrow
var lastKey = "", tId = setInterval(testKey, 5000);
window.onkeydown = KeyPressed;
function KeyPressed(k) {
lastKey = k.keyCode;
}
function testKey() {
if (lastKey == 39) {
console.log("Arrow pressed as last key in the last 5 secs");
lastKey=""; // clear it for next time
}
}
Check if the arrow has been clicked in the last 5 seconds
var lastKey = "", tId = setInterval(testKey, 5000), arrow = "";
window.onkeydown = KeyPressed;
function KeyPressed(k) {
lastKey = k.keyCode;
if (lastKey == 39) {
arrow = new Date();
console.log("pressed arrow");
}
}
function testKey() {
if (arrow) {
console.log("Arrow pressed at least once in the last 5 secs - at "+arrow);
}
arrow="";
}

Making a timer with code that can easily be reset

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>

Javascript - Check if key was pressed twice within 5 secs

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.

Categories