Control loss with Javascript code - javascript

I wrote this Javascript for a website I am creating and I am not sure why the code runs automatically, one of my solutions is to write a function/create a timer so that the code runs at the time I want it to.
here is the js:
var introCap = document.getElementById("captionCol");
var imgDiv = document.getElementById("imgCol");
var introDiv = document.getElementById("intro");
var expose = document.getElementById("gotoPage");
var fade = 1;
var l = 15;
var r = 45;
//expose.onclick = move; this is commented out for the time being.
function stop() {
clearInterval(moveInt);
clearInterval(fadeInt);
}
function fadeOut() {
fade -= 0.07;
introDiv.style.opacity = fade;
introDiv.style.filter = "alpha('"+fade+"')";
if(introDiv.style.opacity<0) {
stop();
}
}
var fadeInt = setInterval("fadeOut()", 60);
function move() {
l -= 0.1;
r += 0.1;
introCap.style.left = r+"%";
imgDiv.style.left = l+"%";
if (imgDiv.style.left<10) {
fadeOut();
}
}
var moveInt = setInterval("move()", 70);
here is the corresponding html:
<div id="intro">
<div id="imgCol"></div>
<div id="captionCol">
<p> Hi, I'm <b>Jenny Spring</b>. <br><br>
I'm a <span id="emp">SPIN</span> farmer. </p>
</div>
<p>Go To</p> <!-- this link will be changed to a button later but is being used as is temporarily.
</div>
Is anyone able to tell why the code performs automatically?
Thanks!

setInterval() not only sets the interval, but it also calls the function after each interval. So do not use this function until you are ready to call it. Another function, setTimeout() is available, which executes the function only once.
For example, you can move interval calls to a function start() and use your href to act as a start button
function start() {
var moveInt = setInterval("move()", 70);
var fadeInt = setInterval("fadeOut()", 60);
}
<p>Go To</p>
Source: http://www.w3schools.com/js/js_timing.asp

Related

How do you restate setInterval after clearInterval has already been declared?

I realize there are more than a few answers on here about this but this particular instance has a very individual problem. I need to, on click, replay this png sequence after clearInterval has been used.
var myImage = document.getElementById("myImage");
var animationArray = ['assets/calvin_hobbes_dance00.png',
'assets/calvin_hobbes_dance01.png',
'assets/calvin_hobbes_dance02.png',
'assets/calvin_hobbes_dance03.png',
'assets/calvin_hobbes_dance04.png',
'assets/calvin_hobbes_dance05.png',
'assets/calvin_hobbes_dance06.png',
'assets/calvin_hobbes_dance07.png',
'assets/calvin_hobbes_dance08.png',
'assets/calvin_hobbes_dance09.png',
'assets/calvin_hobbes_dance10.png'];
var animationIndex = 0;
function changeImage () {
myImage.setAttribute("src", animationArray[animationIndex]);
animationIndex++;
if (animationIndex >= animationArray.length) {
animationIndex = 10;
clearInterval(intervalHandler);
}
}
var intervalHandler = setInterval(changeImage, 100);
A secondary question, this is merely a code sample. How might I wrap this so I can use it for elements that have animations attached that when upon focus play the animation?
Thank you.
Just add an onclick handler to your image. In the onclick handler, reset the animationIndex to 0, call clearInterval to clear the interval if it is running, and call the setInterval function again.
var myImage = document.getElementById("myImage");
var animationArray = ['assets/calvin_hobbes_dance00.png',
'assets/calvin_hobbes_dance01.png',
'assets/calvin_hobbes_dance02.png',
'assets/calvin_hobbes_dance03.png',
'assets/calvin_hobbes_dance04.png',
'assets/calvin_hobbes_dance05.png',
'assets/calvin_hobbes_dance06.png',
'assets/calvin_hobbes_dance07.png',
'assets/calvin_hobbes_dance08.png',
'assets/calvin_hobbes_dance09.png',
'assets/calvin_hobbes_dance10.png'];
var animationIndex = 0;
function changeImage () {
myImage.setAttribute("src", animationArray[animationIndex]);
animationIndex++;
if (animationIndex >= animationArray.length) {
animationIndex = 10;
clearInterval(intervalHandler);
}
}
myImage.onclick = function() {
animationIndex = 0;
clearInterval(intervalHandler);
intervalHandler = setInterval(changeImage, 100);
};
var intervalHandler = setInterval(changeImage, 100);
To answer your secondary question, you might want to consider another approach because this could get kind of messy and be hard to maintain in the future. Consider learning how to do animations using HTML canvas. Here is a tutorial I found showing how you could create multiple animations: http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In fact, I would advise to change your implementation to use the canvas instead.

JavaScript while loop error: Unexpected token

So I have made a code for some coursework, the code is suppose to start a function on page load which will then run the function of changing the traffic light image on screen. It is suppose to keep on changing forever however the program crashes or fails to load when I try to run. Before you suggest the problem is that the variable used in the condition isnt changed, I have tried to change it in the following code. when I ran it in the chrome debugger this is the thing that came up; 'Uncaught SyntaxError: Unexpected token <'.
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"r.jpg",
"randy.jpg",
"g.jpg",
"y.jpg"
];
var counter = 0;
function start() {
counter = counter + 1;
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=images[counter];
}
var a = 100;
function infinity() {
while (200>a) {
setTimeout(start(), 3000);
}
a = a - 25;
}
</script>
</body>
</html>
Instead of setting while loop and setTimeout, use setInterval. The below code will work I think. It will change the image 100 times
var url="http://www.hdwallpapers.in/thumbs/2017/";
var a=0,Handler;
var images = ["yosemite_national_park_winter_4k-t1.jpg","namib_coastal_desert_4k-t1.jpg","beach_dock-t1.jpg"];
var counter = 0;
function start() {
counter = counter + 1;
a++;
if(a>=100 && Handler)
clearInterval(Handler);
if(counter == images.length) counter=0;
var image = document.getElementById("trafficlight");
image.src=url+images[counter];
return;
}
function infinity() {
Handler=setInterval(start, 3000);
}
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="http://www.hdwallpapers.in/thumbs/2017/yosemite_national_park_winter_4k-t1.jpg">
<script>
</script>
</body>
</html>
I know that this question already has an answer, but i just figured that the following code might be a better and a relatively simpler way of doing it.
<DOCTYPE html>
<html>
<body onload="infinity()">
<p></p>
<h1>Traffic Light Sequence</h1>
<img id ="trafficlight" src="r.jpg">
<script>
var images = [
"red.JPG",
"green.jpg",
"randy.jpg",
"yellow.JPG"
];
function infinity() {
var counter = 0,
image = document.getElementById("trafficlight"),
a = 5,
timeoutInterval = 3000;
setInterval(function() {
counter++;
if(counter == images.length) counter=0;
if (a>=0) {
image.src=images[counter];
a--;
}else{
// this else case is in the event that the timeout
// variable is 1, which is essentially 1ms, which
// is bad as it would make your cpu usage go to a
// 100%
if (timeoutInterval <= Number.MAX_SAFE_INTEGER - 2) {
// the above if condition is to stop timeoutInterval
// from ever reaching 2^53 which would cause an
// overflow
timeoutInterval *= 2;
Math.pow(timeoutInterval, 20);
}
}
}, timeoutInterval);
}
</script>
</body>
</html>
Thanks!
P.S. my laptop is still hot from running your infinite loop code of an example

Manual traffic light conversion into automatic via Javascript

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input . I have now got the code working but it only runs through once and then stops so how can I change this so it keeps going? Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
}
</script>
</head>
<body>
<img id="img" src="image1.jpg">
</body>
</html>
To make this automatic, you can either put it in a loop, or you can use the setInterval function.
var interval = setInterval(nextLightClick, 1500);
This will loop indefinitely, running the function every 1500 milliseconds (1.5 seconds). If you want to stop it, you can simply say:
clearInterval(interval);
Here's an example -- note that I am changing the innerHTML, rather than the src, and I am using a div instead of image, but the logic will be exactly the same.
var tlight = new Array("1green.jpg","2yellow.jpg","3red.jpg");
var index = 0;
var tlightLen = tlight.length;
var image = document.getElementById('firstlight');
image.innerHTML = tlight[index];
var interval;
function startInterval() {
interval = setInterval(nextLightClick, 1500);
}
function stopInterval() {
clearInterval(interval);
}
function nextLightClick() {
index++;
if (index == tlightLen)
index = 0;
image.innerHTML = tlight[index];
}
<span id="firstlight"></span></br>
<button onclick="startInterval()">Start</button>
<button onclick="stopInterval()">Stop</button>

Javascript create an image and make it move

I'm trying to make a little browser game where you can shoot bullets.
Right now I am able to make a bullet, but I don't know how to get in moving.
I have done this:
var bullet_id = 1;
var timer_id; // reference of the timer, needed to stop it
var speed = 350; // pixels/second
var period = 10; // milliseconds
var sprite; // the element that will move
var sprite_speed = 0; // move per period
var sprite_position = 315; // pixels
function createbullet() {
var img = document.createElement("img");
img.src = "images/bullet.png";
img.id = "bullet";
img.name = "bullet";
var foo = document.getElementById("fooBar");
foo.appendChild(img);
move(1);
bullet_id++;
}
function animate ()
{
document.getElementById("bullet").style.left=340 + "px";
sprite_position += sprite_speed;
sprite.style.left = sprite_position+'px';
}
function move(direction)
{
if (timer_id) stop();
sprite_speed = speed * period/1000 * direction;
timer_id = setInterval (animate, period);
}
function stop()
{
clearInterval (timer_id);
timer_id = null;
}
function init()
{
sprite = document.getElementById ("bullet"); // the HTML element we will move
animate(); // just to initialize sprite position
}
window.onload = init; // start doing things once the page has loaded */
I tried to add a bullet_id system but I couldn't get it working really.
Here is my html
<a onmousedown="document.jack.src=image2.src;" onmouseup="document.jack.src=image1.src;" onclick="createbullet()"><img id="jack" name="jack" src="/images/jack1.png" /></a>
<div id="fooBar"></div>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('jack').addEventListener('click',function(){...})
Ok so maybe I didn't think that one through, have just designed one to see if I could and it works, hope it helps:
/********************************************************/
stg=0
bgx=0
spd=70
buls=0
act=false
/********************************************************/
function ani(){
var int
act=true
bgx-=52
stg++
$('#jack').css('background-position','-52px 0px')
int=setInterval(function(){
if(stg<4){bgx-=52; stg++}
else{ bgx=0; stg=0 }
$('#jack').css('background-position',bgx+'px 0px')
if(stg==4) new Bullet();
if(!stg){
act=false
clearInterval(int)
}
},spd)
}
/********************************************************/
function Bullet(){
var x,img,int
x=52
img=document.createElement('img')
img.src='bullet.png'
img.setAttribute('class','mh posAbs')
img.setAttribute('style','top:0px;left:'+x+'px')
img.setAttribute('id','bul'+buls)
scre.appendChild(img)
img=document.getElementById('bul'+buls)
buls++
int=setInterval(function(){
if(x<300){
x+=13
img.setAttribute('style','top:0px;left:'+x+'px')
}
else{
img.src='exp.png'
clearInterval(int)
setTimeout(function(){ scre.removeChild(img) },100)
}
},spd)
}
/********************************************************/
$(document).ready(function(){
$('html').keydown(function(){
if(!act){
if(event.keyCode==13) ani();
}
})
$('html').click(function(){
if(!act) ani();
})
})
/********************************************************/
<div id="scre" class="posRel">
<div id="jack"></div>
</div>
<style>
#jack{
width:52px;
height:37px;
background:url('02.png') no-repeat;
background-position:0px 0px;
background-size:auto 100%
}
</style>
Ok so what's happening above is every time you click or press Enter, the firing animation is called, which is animated in stages and when it gets to a certain stage it calls upon the Bullet() constructor to create a new Object or bullet.
While creating the bullet, the constructor generates an <img> and gives it a unique id based upon the buls variable, which is then incremented to keep the id's unique.
This is the most important part:
img=document.getElementById('bul'+buls)
It will NOT work without it as any references to img in the code after it will refer to the last img created and not say:- 'bullet 5 of 10 that are on screen'.
Once created the Bullet object handles the movement of the image it is referenced to, removing the need to move it with any other code...
P.S. The $('html').keydown(...) acts as an auto-fire!

JQuery progress bar pauses when browser tab is changed

I'm trying to display a progress bar on a html page using javascript. However,
when the browser tab containing the code becomes inactive, the progress bar stops updating,
being resumed when the tab is active again.
How can I prevent the browser from stopping/pausing the execution of javascript code when the window is inactive?
Although it may be irrelevant, here is the code:
Object.progressBar = function(){
$( "#question-progress-bar" ).progressbar({
value: false,
complete: function(event, ui) { ... }
});
var seconds = 15.0,
progressbar = $("#question-progress-bar"),
progressbarValue = progressbar.find(".ui-progressbar-value");
progressbarValue.css({
"background": '#c5b100',
"opacity" : '0.8'
})
var int = setInterval(function() {
var percent = (15-seconds)/15*100;
seconds=seconds-0.1;
progressbar.progressbar( "option", {
value: Math.ceil(percent)
});
$("#question-progress-bar-seconds").html((seconds).toFixed(1)+"s");
if (seconds <= 0.1) {
clearInterval(int);
}
}, 100);
}
Instead of using setInterval and assuming a certain amount of time has passed between calls (even when it's up front, setInterval has hit or miss accuracy) use the Date object to get a time when the bar starts, and compare that to the current time at each iteration.
<html>
<head>
<script>
function go()
{
var pb = new ProgressBar(5, "targ");
}
window.onload = go;
function ProgressBar(l, t)
{
var start = Date.now();
var length = l * 1000;
var targ = document.getElementById(t);
var it = window.setInterval(interval, 10);
function interval()
{
var p = 100 * (Date.now() - start) / length;
if(p > 100)
{
p = 100;
window.clearInterval(it);
alert("DONE"); // alternatively send an AJAX request here to alert the server
}
targ.value = (Math.round(p) + "%");
}
}
</script>
</head>
<body>
<input type="text" id="targ" />
</body>
</html>
I've made an example object, here, that immediately starts a countdown when instantiated and calls an alert and kills the interval timer when done. Alternatively an AJAX call, or any other sort of call can be done upon completion.
It should be noted that this will NOT complete the call if the browser stops Javascript all together. It will, however, complete it as soon as the tab has been given focus again if enough time has passed in the interim. There is no way for a website to alter this sort of browser behavior from the scripting side.
Hope that helps!

Categories

Resources