how to set only one key for stop/start setInterval function - javascript

I have function for stop and start the setInterval with key .
it's starts with S key and stops with Z key .
var refreshIntervalId;
window.addEventListener("onkeydown", keyDown,true);
window.addEventListener("keydown", keyDown);
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
start();
break;
case 90:
stop();
break;
}
}
function start() {
stop();
refreshIntervalId = setInterval(function() {
// code...
},10);
}
function stop() {
if (refreshIntervalId != null) {
clearInterval(refreshIntervalId);
refreshIntervalId = null;
}
}
So how can i set only Z key for start and stop the SetInterval ??
for example i press Z key and it starts then i press Z key again and it stops !
anyone can help me ?

Modify your code like below,
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 90:
if(refreshIntervalId) {
stop();
}
else {
start();
}
break;
}
}
Check if refreshIntervalId is a truthy value. If it is then stop the interval else start it.

var boolStart = false;
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
if(!boolStart){
start();
}else{
stop();
}
break;
}
}
function start() {
stop();
boolStart = true;
..
}
function stop() {
boolStart = false;
....
}
EDIT 1:
You can do in this way also.
var boolStart = false;
function keyDown() {
var e = window.event;
switch (e.keyCode) {
case 83:
//;
boolStart = !boolStart;
if (!boolStart) {
start();
} else {
stop();
}
break;
}
}

Related

Clear interval not working on javascript timer

Here is my code
document.addEventListener("keydown", move);
function move(e) {
switch (e.keyCode) {
case 37:
x = x - speed;
break;
case 38:
// up key pressed
y = y - speed
break;
case 39:
x = x + speed
break;
case 40:
y = y + speed
break;
case 32:
if (iTouched == true) {
startCounter();
}
break;
}
sendData();
}
document.addEventListener("keyup", getStuff);
function getStuff(e) {
switch (e.keyCode) {
case 32:
if (iTouched == true) {
shoot();
}
break;
}
}
function startCounter() {
function count() {
time += 1
console.log(time)
}
interval = setInterval(count, 100)
}
function shoot() {
clearInterval(interval)
}
The startCounter() function is triggered by a keydown event listener and the shoot() function is triggered by a keyup event listener. For some reason the setInterval will not stop when I lift the key up. The shoot() function works with other commands like an alert() just not the clearInterval(). Am I doing something wrong? Thanks!
Keydown fires multiple times as you hold down the key.
var bod = document.body;
bod.addEventListener("keydown", () => console.log('keydown', new Date()))
bod.addEventListener("keyup", () => console.log('keyup', new Date()))
So you create more than one interval so you overwrite the last one. So you need to clear the interval before you create a new one
if (interval) clearInterval(interval)
interval = setInterval(count, 100)
or do not create one if it exists
if (!interval) {
interval = setInterval(count, 100)
}
and when you clear it
function shoot() {
clearInterval(interval)
interval = null
}

Make it work only with left mouse down

Holla ,
this is the javascript im using
var timeoutID;
function setup() {
document.getElementById("demo").addEventListener("mousedown", resetTimer);
startTimer();
}
setup();
function startTimer() {
timeoutID = window.setTimeout(goInactive, 1000);
}
function resetTimer() {
window.clearTimeout(timeoutID);
goActive();
}
function goInactive() {
document.getElementById("demo").style.opacity = 0;
document.getElementById("demo").style.transition = "1s";
}
function goActive() {
document.getElementById("demo").style.opacity = 1;
document.getElementById("demo").style.transition = "1s";
startTimer();
}
everything is working fine , except i want it to go active only by left mouse button ( now right click left click and middle click are doing the job )
So many thanks in advance
AliYous
You have to detect the left mouse button press by checking the event object (Detect left mouse button press).
evt = evt || window.event;
if ("buttons" in evt) {
return evt.buttons == 1;
}
And then if it's left mouse (1), proceed to do your job in resetTimer() function. Final code will be:
function resetTimer(e) {
evt = e || window.event;
if ("buttons" in evt) {
if (evt.buttons == 1) {
window.clearTimeout(timeoutID);
goActive();
}
}
}
You can use the mouseup event on the element you want to use as the trigger.
You haven't said what you click so I used document in the example below.
The below example is taken pretty much straight from the Mouse Event Button Documentation
document.addEventListener('mouseup', function(e) {
var e = e || window.event;
var btnCode;
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left button clicked.');
break;
case 1:
console.log('Middle button clicked.');
break;
case 2:
console.log('Right button clicked.');
break;
default:
console.log('Unexpected code: ' + btnCode);
}
})
The short version more applicable to your scenario could look like the blow:
var resetTimer = function() {
console.log('resetTimer called');
};
document.addEventListener('mouseup', function(e) {
var e = e || window.event;
var btnCode;
btnCode = e.button;
if (btnCode === 0) {
resetTimer();
}
})

Is a function stored in memory once it is called?

I know there are many solutions with this type of question but somehow they are very complex.
I wanted to know what happens once a function is called. For example, in my sample code, when I call keyboardHandler() once, the eventHandler will add the keyPressed() and keyReleased() functions to the keydown and keyup events. But since they are not global functions (but defined inside another function), will I be able to access them outside, in the global area, when a key is pressed?
If yes, does that mean a function once called is somewhat stored in the memory?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var leftPressed = false;
var upPressed = false;
var rightPressed = false;
var downPressed = false;
function keyboardHandler() {
document.addEventListener("keydown", keyPressed);
document.addEventListener("keyup", keyReleased);
function keyPressed(e) {
switch(e.keyCode) {
case 37:
leftPressed = true;
break;
case 38:
upPressed = true;
break;
case 39:
rightPressed = true;
break;
case 40:
downPressed = true;
break;
}
}
function keyReleased(e) {
switch(e.keyCode) {
case 37:
leftPressed = false;
break;
case 38:
upPressed = false;
break;
case 39:
rightPressed = false;
break;
case 40:
downPressed = false;
break;
}
}
}

Jquery: count using setInterval

Im trying to create two counter when I press downKey I want to counter1 start counting and when I press keyLeft I want to stop the first counter and start counter2 .... I know that I need to use clearInterval() function but I dont know where I need to use it, here is a JSFiddle
to see what I mean
html:
<div id="left"></div>
<div id="down"></div>
js:
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
var right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
var down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
You need to declare down_move and right_move outside of keydown:
var right_move, down_move;
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
it seems like a scope issue, here is how I would make it:
updated fiddle
var Interval = function(intervalFunc, selector){
var interval;
this.start = function(){
interval = setInterval(intervalFunc, 1000);
},
this.stop = function(){
clearInterval(interval);
}
}
var i = 0;
var rightBtnInterval = new Interval(function downInterval(){
$('#right').html(i)
i++;
});
var j = 0;
var downBtnInterval = new Interval(function downInterval(){
$('#down').html(j)
j++;
});
$('body').keydown(function (e) {
switch (e.which) {
case 39:
rightBtnInterval.stop();
downBtnInterval.start();
break;
case 40:
downBtnInterval.stop();
rightBtnInterval.start();
break;
default:
}
e.preventDefault();
});
You have to store outside of function the interval to stop.
Warning the ascii code of left is 37.
Here is a JSFiddle to see my change:
var storeInterval = null;
$('body').keydown(function (e) {
switch (e.which) {
case 37:
clearInterval(storeInterval);
var i=0;
storeInterval = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(storeInterval);
var j = 0;
storeInterval = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
<div id="left"></div>
<div id="down"></div>

javascript keypress to control animation

Space Invader game: I want to control the 'base gun' (move it left and right and fire missiles at the invaders. So I need a keypress or (keydown?) event to change a variable (x coordinate) and a key press event to fire a missile.
Can anyone show me how the keypress event is detected and the variable is changed?
document.onkeydown = function(e) {
var key = e.keyCode;
if (key===37) {//left arrow pressed
} else if (key===39) {//right arrow pressed
}
}
Like this?
document.onkeydown = checkKey;
var xCoord = 100;
function checkKey(e) {
e = e || window.event;
switch (e.keyCode) {
case 37 : // left
xCoord -= 5;
break;
case 39 : // right
xCoord += 5;
break;
}
}
Exciting fiddle: http://jsfiddle.net/u5eJp/
Couple things I would like to add to the other answers:
1) Use constants to make it easier on yourself
2) There is no way to check if a key is currently pressed in javascript, so you should keep track of what is currently pressed as well
var pressed = {
up: false,
down: false,
left: false,
right: false
};
var LEFT_ARROW = 37;
var UP_ARROW = 38;
var RIGHT_ARROW = 39;
var DOWN_ARROW = 40;
document.onkeydown = function (e) {
e = e || window.event;
switch (e.keyCode) {
case LEFT_ARROW:
pressed.left = true;
break;
case UP_ARROW:
pressed.up = true;
break;
case RIGHT_ARROW:
pressed.right = true;
break;
case DOWN_ARROW:
pressed.down = true;
break;
default:
break;
}
}
//update position separately
function updatePos() {
if (pressed.up) { //change y up }
if (pressed.down) { //change y down }
if (pressed.left) { //change x left }
if (pressed.right) { //change x right }
}
Hope this helps, and good luck!

Categories