Starting/Pausing canvas animation with a button click - javascript

I am trying to get a simple snake game running where the game is off default and you click Start to begin.
the StartStop button's code:
StartStop.onclick = function()
{
//flip the name on the button
if (StartStop.value = "Start")
{
StartStop.value = "Stop";
update();
}
else
{
StartStop.value = "Start";
clearInterval(update);
}
}
code inside update() starts the animation:
function update()
{
setInterval(function()
{
console.log(snake.x + ", " + snake.y);
//check for collisions
//if no collisions move and draw snake
snake.x += velocity[vi][0];
snake.y += velocity[vi][1];
snake.draw();
},30);
}
My thought process was when the button's text value is Start, it changes the text to Stop and calls update() which calls setInterval().
Then when you click the button and the text value is Stop, it calls clearInterval(timer) to stop the animation
I think I am not using setInterval correctly, any ideas on how to get it to start and stop on a button click?

I fixed it by changing my code to this:
StartStop.onclick = function()
{
if (StartStop.value == "Start")
{
StartStop.value = "Stop";
var timer = setInterval(
function()
{
if (StartStop.value == "Stop")
{
console.log(snake.x + ", " + snake.y);
//check for collisions
//if no collisions move and draw snake
snake.x += velocity[vi][0];
snake.y += velocity[vi][1];
snake.draw();
}
else
{
clearInterval(timer);
}
},30);
}
else
StartStop.value = "Start";
}

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);
}
}
}
}

How to create a JavaScript animation loop that stops when another starts playing?

How to create an animation loop that spins for a while and calls another animation, and when another animation starts working, the first one waits for the other to finish, and when the other animation has finished its work, the first one starts playing again, and so on in a circle. As I understand it, it is problematic to do this through setTimout(in recursion), since they overlap each other and cannot wait for the completion of the other.
That's what I tried to do:
var func = function(i) {
return function() {
if (i >= 5) return;
console.log("turn no. " + i);
// running second recursion
var func2 = function(i_) {
return function() {
if (i_ >= 75) return;
console.log("turn no2. " + i_);
if (i_ >= 75) {
console.log('2 Player won');
} else {
setTimeout(func2(++i), 2000);
}
}
}
setTimeout(func2(0), 2000);
// end running second recursion
if (i >= 5) {
console.log('1 Player won');
} else {
setTimeout(func(++i), 100);
}
}
}
setTimeout(func(0), 100);

Executing the function appear() appear inside If statement

//Blinking of the letter " X " on the Screen
function blink() {
document.getElementById('blinkText').innerHTML = "";
setTimeout("appear()", Math.random() * 3000);
}
//Re-Appearing of the letter " X " on the Screen
function appear() {
document.getElementById('blinkText').innerHTML = "X";
setTimeout("blink()", Math.random() * 3000);
return true;
}
// Counts the number of times a space bar is hit
var hit = 0;
window.onload = function hitSpace() {
document.body.onkeyup = function(e) {
if (e.keyCode == 32) {
hit = hit + 1;
document.getElementById("count").innerHTML = hit;
}
}
blink();
}
//To run function hitSpace() only when the letter "X" appears, else display
alert
function checkForBlink() {
if (appear() == true) {
hitSpace();
} else {
alert("You are too slow!")
}
}
basically what i cant do is, when the letter X appears on the screen i want to count using the function hitSpace() and if the spacebar is hit when the letter X is not there, display an alert message. Please help to rectify my function checkForBlink()
You don't need to call hitSpace(). Check if the X is there in the onkeyup function.
window.onload = function() {
document.body.onkeyup = function(e) {
if (e.keyCode == 32) {
if (document.getElementById("blinkText").innerHTML == "X") {
hit = hit + 1;
document.getElementById("count").innerHTML = hit;
} else {
alert("Sorry, you're too slow");
}
}
}
blink();
}

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>

Categories