How to change the time in setInterval with an user input? - javascript

I want to know a way to change the setInterval time so my image would move across the screen at that pace. Example if i put in 500 milliseconds it would change the time interval from 250 to 500 when i click a button. Here is what I came up with so far.
var x;
var y;
var timing = 1000;
function window_onLoad() {
x = 0;
y = 100;
window.setInterval("MoveBall()", timing);
picBall.style.top = y + "px";
}
function MoveBall() {
x = x + 5;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
}
window_onLoad()
<img id="picBall" src="Face.jpg" style="position: absolute;"/>
<input id="btnReset" type="button" value="Reset position"
onclick="btnReset_OnClick()"/>
<input id="txtSpeed" type="text"/>
<input id="btnSpeed" type="button" value="Change Speed"
oclick="btnSpeed_onClick()"/>

I suggest not to mix moving speed with framerate (your setInterval speed). You can have a fixed framerate and variable speed. E.g.
var speed = 1, timer, x,y;
function window_onLoad() {
x = 0;
y = 100;
window.setInterval("MoveBall()", 100); // 10 frames per second
picBall.style.top = y + "px";
}
function MoveBall() {
x = x + speed;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
/*
speed = 200 will move tbe ball by 20px per sec
speed = 100 will move the ball by 10px per sec
speed = 50 will move the ball by 5px per sec
*/
speed = parseInt(txtSpeed.value)/100;
}

Your main issue is that you need to clear the previous interval and create a new one. However, I'd recommend moving your code that creates the interval into another function like this...
function window_onLoad() {
x = 0;
y = 100;
createInterval(timing);
picBall.style.top = y + "px";
}
var intervalId = 0;
// this will destroy any existing interval and create a new one
function createInterval(interval) {
clearInterval(intervalId);
intervalId = setInterval(MoveBall, interval);
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
createInterval(timing);
}

You have to save a reference to interval and then, every time you want to change the speed you have to clear the previous interval with clearInterval and then apply a new interval, like this:
var x;
var y;
var timing = 1000;
var interval;
function window_onLoad() {
x = 0;
y = 100;
applyInterval();
picBall.style.top = y + "px";
}
function applyInterval() {
if (interval) {
console.log('Clearing previous interval');
clearInterval(interval);
}
console.log('Applying new interval');
interval = window.setInterval("MoveBall()", timing);
}
function MoveBall() {
x = x + 5;
if (x < document.body.clientWidth - 91) {
picBall.style.left = x + "px";
}
}
function btnReset_OnClick() {
x = 0;
}
function btnSpeed_OnClick() {
timing = parseInt(txtSpeed.value);
applyInterval();
}
window_onLoad()
<img id="picBall" src="https://i.stack.imgur.com/vnucx.png?s=64&g=1" style="position: absolute;" width="25" height="25"/>
<input id="btnReset" type="button" value="Reset position"
onclick="btnReset_OnClick()"/>
<input id="txtSpeed" type="text"/>
<input id="btnSpeed" type="button" value="Change Speed"
onclick="btnSpeed_OnClick()"/>

Related

How do I use a repeat function to reset everything and run everything over again?

I have a repeat function which runs on a button on-click event, however it's not working properly. Maybe because there are too many setIntervals running although I tried to clear them all. I also made sure to reset the variables used back to their initial values, however the moving circle keeps showing up faded when the shoot again button is pressed, so I'm assuming there's an issue with the setInterval, however, I don't know what it is.It's also not drawing the basketball again.
var level = prompt("Type 1 for hard, 2 for medium, and 3 for easy.")
var dt = level / 100;
var ctx = canvas.getContext("2d");
var intervalId2;
var intervalId1;
//Initializing Variables
var dt = level / 100;
const PI = 3.14;
var r = 20;
var x = r + 1;
var y = 500 / 1.2;
var a = 1;
var shift = 380;
var leftshift = 35;
var xc = 145;
var yc = 300;
var rc = 50;
var dxc = 95;
var dyc = 300;
var theta = 0;
var resetVars = function() {
dt = 0.01;
var x = r + 1;
var y = 500 / 1.2;
var xc = 145;
var yc = 300;
var dxc = 95;
var dyc = 300;
var theta = 0;
};
//resetVars();
var reset = function() {
ctx.clearRect(0, 0, 800, 800);
drawHoop()
};
//Interval Id to eventually clear it to stop this to shoot
var intervalID = setInterval(moveCirc, 10000 * dt);
var count = 0;
//shoot when spacebar is pressed
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
var repeat = function() {
reset();
clearInterval(intervalID);
clearInterval(intervalId2);
clearInterval(intervalId1);
resetVars();
drawBasketball();
drawHoop();
moveCirc();
intervalID = setInterval(moveCirc, 10000 * dt);
document.body.onkeyup = function(shoot1) {
if (dxc <= 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
make();
count = count + 1;
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
if (dxc > 110 && shoot1.keyCode == 32) {
console.log(dxc);
clearInterval(intervalID);
miss();
document.getElementById("count").innerHTML = "You've made " + count + " baskets.";
}
};
};
<html>
<canvas id="canvas" width="1000" height="500"> </canvas>
<body style="background-color:powderblue;">
<p id="count"></p>
<button id="again" onclick="repeat()"> Shoot Again </button>
</body>
This should make a stop button for a repeating function
<script>
var int=self.setInterval(function, 60000);
</script>
<!-- Stop Button -->
Stop

Cannot change element.style.height value with loop

The code only changes the element's height value at the end of the loop, which means no animation :,(
The code is like following:
function heightenElement(id,interval,step,height,unit) {
y = 0;
function loop() {
y = y + step;
thing = y + unit;
console.log(y);
if (y < height) {
document.getElementById(id).style.height = thing;
setTimeout(loop(),interval);
}
}
loop();
}
An answer would be appreciated :)
setTimeout accepts a function as a parameter - if you put a function call in there, the function will be executed immediately. Simply pass the function name instead:
function heightenElement(id, interval, step, height, unit) {
let y = 0;
function loop() {
y = y + step;
thing = y + unit;
console.log(y);
if (y < height) {
document.getElementById(id).style.height = thing;
setTimeout(loop, interval);
}
}
loop();
}
heightenElement('div', 500, 10, 100, 'px');
div {
height: 30px;
background-color: yellow;
}
<div id="div">
</div>

HTML5 Javascript game

I'm trying to make a HTML5 game in javascript. Similar to pong, but once the bubble hits the paddle or bottom screen it "bursts" or disappears. I cant seem to get the Bubble to disappear or burst in my code. Could anyone help me?
var canvasColor;
var x,y,radius,color;
var x=50, y=30
var bubbles=[];
var counter;
var lastBubble=0;
var steps=0, burst=0, escaped=0;
var batonMovement = 200;
var moveBatonRight = false;
var moveBatonLeft = false;
function startGame()
{
var r,g,b;
var canvas,color;
//Initialize
canvasColor = '#EAEDDC';
x = 10;
y = 10;
radius = 10;
clearScreen();
counter=0;
while (counter <100)
{
//make bubble appear randomly
x=Math.floor(Math.random()*450)
//Set up a random color
r = Math.floor(Math.random()*256);
g = Math.floor(Math.random()*256);
b = Math.floor(Math.random()*256);
color='rgb('+r+','+g+','+b+')';
bubbles[counter] = new Bubble(x,y,radius,color);
counter+=1;
}
setInterval('drawForever()',50);
}
function Bubble (x,y,radius,color)
{
this.x=x;
this.y=y;
this.radius=radius;
this.color=color;
this.active=false;
}
function drawForever()
{
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
steps +=1
clearScreen();
if (steps%20==0 && lastBubble < 100){
bubbles[lastBubble].active=true;
lastBubble +=1;
}
drawBaton();
counter=0;
while (counter <100)
{
if (bubbles[counter].active==true){
pen.fillStyle = bubbles[counter].color;
pen.beginPath();
pen.arc(bubbles[counter].x,
bubbles[counter].y,
bubbles[counter].radius,
0,
2*Math.PI);
pen.fill();
bubbles[counter].y+=2;
}
if (y>=240 && y<=270 && x>=batonMovement-10 && x<=batonMovement+60)
{
bubbles[lastBubble]=false;
}
else if (y>=450)
{
bubbles[lastBubble]=false;
}
counter +=1;
}
}
function clearScreen()
{
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
pen.fillStyle = canvasColor;
pen.fillRect(0,0,450,300);
}
function drawBaton()
{
var canvas, pen;
if (moveBatonLeft == true && batonMovement > 0)
{
batonMovement -= 20;
}
else if (moveBatonRight == true && batonMovement < 400)
{
batonMovement += 20;
}
//draw Baton (rectangle)
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
pen.fillStyle = '#0000FF';
pen.fillRect(batonMovement,250,50,10);
}
function moveLeft()
{
moveBatonLeft=true;
}
function moveRight()
{
moveBatonRight=true;
}
function stopMove()
{
moveBatonLeft=false;
moveBatonRight=false;
}
Below is the HTML code...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bubble Burster</title>
<script type="text/javascript" src="project.js"></script>
</head>
<body onload="startGame();">
<div style="text-align:center;">
<h2>Bubble Burster</h2>
<canvas id="myCanvas" width="450" height="300" style="border:5px solid #000000; background-color: #f1f1f1;">
Your browser does not support the canvas element.
</canvas><br>
<button onmousedown="moveLeft();" onmouseup="stopMove();">LEFT</button>
<button onmousedown="moveRight();" onmouseup="stopMove();">RIGHT</button><br><br>
<form>
<input type="radio" name="difficulty" value="easy" onclick="check(this.value);" checked> Easy
<input type="radio" name="difficulty" value="moderate" onclick="check(this.value)"> Moderate
<input type="radio" name="difficulty" value="hard" onclick="check(this.value)"> Hard <br><br>
</form>
<span id="burst">Burst:</span>
<span id="escaped">Escaped: </span>
<span id="steps">Steps elapsed:</span>
<h3 id="output"></h3>
</div>
</body>
</html>
You are referring to x, y which are not defined in the drawForever function. The global values of x and y may not refer to the right bubble. In fact y is set to 10 in the startGame function and never altered subsequently. You also probably want to refer to bubbles[counter] rather than bubbles[lastBubble]. The game seems to work if you make the changes below, referring to bubbles[counter].x and bubbles[counter].y instead of x and y.
function drawForever() {
var canvas, pen;
canvas = document.getElementById('myCanvas');
pen = canvas.getContext('2d');
steps += 1
clearScreen();
if (steps % 20 == 0 && lastBubble < 100) {
bubbles[lastBubble].active = true;
lastBubble += 1;
}
drawBaton();
counter = 0;
while (counter < 100) {
if (bubbles[counter].active == true) {
pen.fillStyle = bubbles[counter].color;
pen.beginPath();
pen.arc(bubbles[counter].x,
bubbles[counter].y,
bubbles[counter].radius,
0,
2 * Math.PI);
pen.fill();
bubbles[counter].y += 2;
}
y = bubbles[counter].y; // ADDED (y was not defined in original code)
x = bubbles[counter].x; // ADDED (x was not defined in original code)
if (y >= 240 && y <= 270 && x >= batonMovement - 10 && x <= batonMovement + 60) {
bubbles[counter] = false; // ALTERED (burst the current bubble, not whatever lastBubble refers to
} else if (y >= 450) {
bubbles[counter] = false; // ALTERED (burst the current bubble, not whatever lastBubble refers to
}
counter += 1;
}
}
https://jsfiddle.net/acLot87q/4/
You should also make x and y local variables within each function; they are not currently serving the purpose that you seem to think.

Javascript setInterval randomly stops

I'm using setInterval to call a function that animates a fractal on a HTML5 canvas. There is also a slider to allow the user to change the quality of the fractal. Everything works fine until I start changing the slider. When I change it, the fractal animation becomes choppy, and eventually the "drawFractal" function stops being called.
Here is the slider HTML:
<input type="range" id="qualitySlider" min="1" max="10"></input>
Here is the javascript (it just generates a fractal):
var count = 0.5;
var slider = document.getElementById("qualitySlider");
var g = document.getElementById("drawingCanvas").getContext("2d");
function drawFractal() {
var cellSize = Math.ceil(slider.value);
//canvas is 700 by 400
g.fillStyle = "black";
g.clearRect(0, 0, 700, 400);
//Eveything from here to the end of this function generates the fractal
var imagC = Math.cos(count)*0.8;
var realC = Math.sin(count)*0.5;
for (x = 0; x < 700; x+=cellSize) {
for (y = 0; y < 400; y+=cellSize) {
var yCoord = (x / 700.0 - 0.5)*3;
var xCoord = (y / 400.0 - 0.5)*3;
var real = xCoord;
var imag = yCoord;
var broken = 0;
for (i = 0; i < 8; i++) {
var temp = real*real - imag*imag + realC;
imag = 2*imag*real + imagC;
real = temp;
if (real*real + imag*imag >= 4) {
broken = true;
break;
}
}
if (!broken) {
g.fillRect(x, y, cellSize, cellSize);
}
}
}
count = count + 0.04;
}
setInterval(drawFractal, 60);
I just need the "drawFractal" function to be called reliably every 60 milliseconds.
This is my improved code. I just used requestAnimationFrame to recursively call the "drawFractal" function. I also restricted the animation to 24 frames/sec with the setTimeout function.
var count = 0.5;
var qualitySlider = document.getElementById("qualitySlider");
var g = document.getElementById("drawingCanvas").getContext("2d");
function drawFractal() {
var cellSize = Math.ceil(qualitySlider.value);
//canvas is 700 by 400
g.fillStyle = "black";
g.clearRect(0, 0, 700, 400);
var imagC = Math.cos(count)*0.8;
var realC = Math.sin(count)*0.5;
for (x = 0; x < 700; x+=cellSize) {
for (y = 0; y < 400; y+=cellSize) {
var yCoord = (x / 700.0 - 0.5)*3;
var xCoord = (y / 400.0 - 0.5)*3;
var real = xCoord;
var imag = yCoord;
var broken = 0;
for (i = 0; i < 8; i++) {
var temp = real*real - imag*imag + realC;
imag = 2*imag*real + imagC;
real = temp;
if (real*real + imag*imag >= 4) {
broken = true;
break;
}
}
if (!broken) {
g.fillRect(x, y, cellSize, cellSize);
}
}
}
count = count + 0.04;
setTimeout(function() {
requestAnimationFrame(drawFractal);
}, 41);
}
drawFractal();
You are using setInterval() to call drawFractal every 60 ms, and then every time drawFractal is executed, you're calling setInterval() again, which is unnecessary. You now have two timers attempting to draw fractals every 60 ms... then you'll have 4, then 8, etc.
You need to either (1) call setInterval() once at the start of program execution and not call it again, or (2) switch to using setTimeout(), and call it at the end of each drawFractal().
I'd use the second option, just in case your fractal ever takes more than 60 ms to draw.

JavaScript rectangle follow cursor in menu

I wrote a code in JS for my future site and it's all fine but the only bad thing here is in menu the rectangle (div) moves with brakes. I mean it must be like in a site some features of which I want to have on my own. http://lusens.ru/ There on main menu the rectangle mouse very smoothly. I can't understand why in my case it doesn't happen.
This is a part of html
<body>
<ul >
<li id="a1" onmouseover="highlightMenu('a1')">Первый пункт</li>
<li id="a2" onmouseover="highlightMenu('a2')">Второй пункт точка</li>
<li id="a3" onmouseover="highlightMenu('a3')">Третьий пункт точка и запятая</li>
<li id="a4" onmouseover="highlightMenu('a4')">Четвёртый пункт</li>
</ul>
<div id="d1"></div>
and the JS file
function highlightMenu(id) {
time = 0;
var rect = document.getElementById(id).getBoundingClientRect();
var width = document.getElementById(id).offsetWidth;
var idTop = rect.top;
var idLeft = rect.left;
var rect1 = document.getElementById('d1').getBoundingClientRect();
var shadowWidth = document.getElementById('d1').offsetWidth;
var shadowLeft = rect1.left;
var shadowTop = rect1.top;
if (shadowLeft < idLeft) {
for (i = shadowLeft, time = 50; i < idLeft - 3; i++, time += 5) {
setTimeout("document.getElementById('d1').style.left='" + i + "px'", time);
}
} else {
for (i = shadowLeft, time = 50; i > idLeft - 3; i--, time += 5) {
setTimeout("document.getElementById('d1').style.left='" + i + "px'", time);
}
}
if (shadowWidth < width) {
for (i = shadowWidth; i < width + 10; i++, time += 0.01) {
setTimeout("document.getElementById('d1').style.width='" + i + "px'", time);
}
} else {
for (i = shadowWidth; i > width + 10; i--, time += 0.01) {
setTimeout("document.getElementById('d1').style.width='" + i + "px'", time);
}
}
if (shadowLeft < idLeft) {
for (i = idLeft + 3; i < idLeft + 20; i++, time += 25) {
setTimeout("document.getElementById('d1').style.left='" + i + "px'", time);
}
for (i = idLeft + 20; i > idLeft - 5; i--, time += 50) {
setTimeout("document.getElementById('d1').style.left='" + i + "px'", time);
}
} else {
for (i = idLeft - 3; i > idLeft - 20; i--, time += 25) {
setTimeout("document.getElementById('d1').style.left='" + i + "px'", time);
}
for (i = idLeft - 20; i < idLeft - 5; i++, time += 50) {
setTimeout("document.getElementById('d1').style.left='" + i + "px'", time);
}
}
}
http://jsfiddle.net/m2SBm/
Using the onmouseover causes to fire the event handler function multiple times, here is better to use the onmouseenter event. And also instead of scheduling 50 timeouts, rather use single timeout and global variables, so that the animation will be stoppable.
HTML:
<ul id="menu">
<li>Первый пункт</li>
<li>Второй пункт точка</li>
<li>Третьий пункт точка и запятая</li>
<li>Четвёртый пункт</li>
</ul>
<div id="d1"></div>
Javascript:
var rect, rect1; // rectangles
var shadow; // shadow div
var bpos; // begin position
var epos; // end position
var width, shadowWidth;
var step; // animation step 1..50
var timer = null;
function animateRect() {
step++;
if (step > 50) {
clearInterval(timer);
timer = null;
return;
}
var t = bpos.t + Math.round((epos.t - bpos.t) * step / 50);
var l = bpos.l + Math.round((epos.l - bpos.l) * step / 50);
var w = shadowWidth + Math.round((width - shadowWidth) * step / 50);
shadow.style.top = t + "px";
shadow.style.left = l + "px";
shadow.style.width = w + "px";
}
function highlightMenu(e) {
e = e || window.event; // for IE8,7 compatibility
var item = e.target || e.srcElement; // for IE8,7
if (timer) {
clearInterval(timer);
}
step = 0;
rect = item.getBoundingClientRect();
width = item.offsetWidth;
epos = {
t: rect.top,
l: rect.left
};
rect1 = shadow.getBoundingClientRect();
shadowWidth = shadow.offsetWidth;
bpos = {
t: rect1.top,
l: rect1.left
};
timer = setInterval(animateRect, 5);
}
function init() {
var menu = document.getElementById('menu');
var items = menu.getElementsByTagName('li');
for (var i = 0; i < items.length; i++) {
items[i].onmouseenter = highlightMenu;
}
shadow = document.getElementById('d1');
shadow.style.width = items[0].offsetWidth + 'px';
shadow.style.top = items[0].getBoundingClientRect().top + 'px';
shadow.style.left = items[0].getBoundingClientRect().left + 'px';
}
if (window.addEventListener) {
window.addEventListener('load', init, false);
} else if (window.attachEvent) {
window.attachEvent('onload', init);
}
JSFiddle: http://jsfiddle.net/m2SBm/6/ (using the getBoundingClientRect function)
Update:
To make your menu work correctly also with eventual scrollbars, compute the element offset position rather than using the getBoundingClientRect function as shown in the following answer:
finding element's position relative to the document
Here is additional CSS for transparency in menu:
ul#menu, ul#menu li {
position:relative;
background-color:transparent;
}
#d1 {
z-index:-10;
}
The complete menu here: http://jsfiddle.net/m2SBm/8/

Categories