input only temporary saved in variable, global variable? - javascript

I want to read 2 inputs from user and save it from my program.
When the user types his input value and submits, the function getValue will be called and values will be put into duration and interval. But when initBuffer is called after getValue, it always tell me that duration and interval are still null. I thought they are global variables...
Can somebody please tell me where I am wrong? Thanks a lot.
//main.js
var duration = null;
var interval = null;
function getValue(){
interval = parseInt(document.getElementById('interval').value);
duration = parseInt(document.getElementById('duration').value);
console.log(window.interval);
if(isNaN(window.interval) || isNaN(window.duration) ){
alert("please give 2 values at the same time");
}
console.log("duration: "+ window.duration + "interval:" + window.interval);
}
function start(){
initBuffer();
}
function initBuffer(){
alert(window.duration);
if(window.duration == null){
console.log('duration set to default: 40');
window.duration = 40; //default (min)
}
if(window.interval == null){
console.log('interval set to default: 5');
window.interval = 5; //default
}
numSamples= Math.floor(duration* 60 /interval);
}
<html>
<head>
<meta charset="utf-8">
<title>Graph</title>
</head>
<style>
#start {
position:absolute;
left:1080px;
top: 30px;
width:30px;
height:30px;
background: #2280ff;
font-size: 12px;
color: white;
border-radius: 10px;
padding: 1em;
}
.div-inline{
display: inline
}
</style>
<body>
<form id = "hint">
<div class = "div-inline">
Interval:
<input type="text" name="interval" id = "interval">(s)
</div>
<div class = "div-inline">
Duration:
<input type = "text" name = "duration" id = "duration">(min)
<input type = "submit" value = "submit" onclick = "getValue() return false">
</div>
<br>
(Default: Interval = 5s, Duration = 40 min)
</form>
<script type="text/javascript">
</script>
<div id = "sec1">
<canvas id = "display" width = "1024" height = "300"></canvas>
</div>
<div id = "start" onclick = "start()" >start</div>
<script src = "main.js" charset="utf-8"></script>
</body>
</html>

This is not an answer, just demonstrating that the fault is not in the posted code
// start of posted code
duration = null;
interval = null;
function getValue() {
window.interval = parseInt(document.getElementById('interval').value);
window.duration = parseInt(document.getElementById('duration').value);
if(isNaN(window.interval) || isNaN(window.duration) ){
alert("please give 2 values at the same time");
}
}
function initBuffer(){
if(window.duration == null){
console.log('duration set to default: 40');
window.duration = 40; //default (min)
}
if(window.interval == null){
console.log('interval set to default: 5');
window.interval = 5; //default
}
numSamples= Math.floor(duration* 60 /interval);
}
// end of posted code
// test code
function test() {
console.log(`duration: ${duration}, interval: ${interval}`);
}
test();
function test2() {
console.log(`duration: ${window.duration}, interval: ${window.interval}`);
}
test2()
window.addEventListener("DOMContentLoaded", function() {
document.getElementById('test').addEventListener('click', test);
test();
initBuffer();
test();
duration = 10;
interval = 10;
test();
getValue();
test();
});
<button id="test" type="button">test</button>
<input type="text" id="interval" value="20">
<input type="text" id="duration" value="30">

Related

How to prevent setInterval from being called multiple times simultaneously?

Is there a way to make the setInterval work only once at a time?
My code should work this way:
You manually input the number of the seconds;
The "div" works as a timer and runs till reaching 0.
If you click "Click me" once, it will work as expected.
However, if you click the button multiple times fast enough, the even listener will be working simultaneously as many times as you clicked.
let button = document.getElementById('button');
let input = document.getElementById('input');
let timer = document.getElementById('timer');
function timerRunner () {
let startTime = input.value;
if (startTime <= 0) {
console.log('The number is <=0')
} else {
do {
timer.textContent = startTime;
let counter = startTime;
let interval = setInterval(()=> {
console.log(counter);
counter--;
timer.textContent = counter;
if (counter === 0) {
clearInterval(interval);
}
}, 1000);
} while (typeof (timer.textContent) == "number");
}
}
button.addEventListener('click', timerRunner)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.centeralizer {
display: block;
width: 200px;
margin: 20vh auto;
}
#input {
display: block;
margin-bottom: 35px;
width: 150px;
}
#button {
display: inline-block;
margin-right: 35%;
}
#timer {
display: inline-block;
}
</style>
<script src="index.js" defer></script>
</head>
<body>
<div class="centeralizer">
<input id="input" placeholder="Input the number" type="number">
<button id="button">Click me</button>
<div id="timer">0</div>
</div>
</body>
</html>
You should store the running interval in the upper scope and clear it if the button is pressed again.
const button = document.getElementById('button');
const input = document.getElementById('input');
const timer = document.getElementById('timer');
let interval = null;
function startTimer() {
const startTime = +input.value;
if (startTime <= 0) {
console.log('The number is <= 0');
return;
}
let counter = startTime;
timer.textContent = startTime;
if (interval) clearInterval(interval);
interval = setInterval(() => {
timer.textContent = --counter;
console.log(counter);
if (counter === 0) clearInterval(interval);
}, 1000);
}
button.addEventListener('click', startTimer)
You can add a boolean variable isRunning that tracks whether the timer is running. You set it on when the timer is running and set it off when the timer is done. Check if it's on when the button is clicked, and return if it is. You can prevent multiple instances of the timer being triggered.
let button = document.getElementById('button');
let input = document.getElementById('input');
let timer = document.getElementById('timer');
var isRunning = false;
function timerRunner () {
if(isRunning) {
return; //return if timer is already running
}
isRunning = true; //specify that the timer is running
let startTime = input.value;
if (startTime <= 0) {
console.log('The number is <=0')
} else {
do {
timer.textContent = startTime;
let counter = startTime;
let interval = setInterval(()=> {
console.log(counter);
counter--;
timer.textContent = counter;
if (counter === 0) {
isRunning = false; //specify that the timer is not running and can be run again
clearInterval(interval);
}
}, 1000);
} while (typeof (timer.textContent) == "number");
}
}
button.addEventListener('click', timerRunner)

How to stop this function at the given point?

var counter;
var count = 0;
//var booli = new Boolean("false");
window.onload = function() {
var x = document.getElementsByClassName('banana')
var i;
for (i = 0; i < x.length; i++) {
let y = x[i];
console.log(y);
x[i].onmousedown = debounce(function() {
//if(booli)
//{
start(y.className, y.value.replace(/\s/g, ''));
//};
}, 550);
};
}
function debounce(a, b) {
return function() {
var timer;
clearTimeout(timer);
timer = setTimeout(function() {
a();
}, b);
};
}
function start(clicked_className, cha) {
counter = setInterval(function() {
add(clicked_className, cha);
count++;
}, 90);
}
function end() {
//booli=false;
clearInterval(counter);
}
function add(clicked_className, cha) {
window.document.numeri.outpu.value =
window.document.numeri.outpu.value + cha;
}
#put {
width: 700px;
height: 18px;
font-size=14pt;
}
<!DOCTYPE html>
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
</head>
<body>
<form name="numeri">
<input type="text" id="put" name="outpu">
<input type="button" id="apple" class="banana" value=" 1 " onmouseleave="end()">
<input type="button" id="ada" class="banana" value=" 2 " onmouseleave="end()">
<input type="button" id="aded" class="banana" value=" 3 " onmouseleave="end()">
</form>
</body>
</html>
Hey guys!
Goal: stop the function that writes numbers before it starts writing numbers
without the commented things the program works, but its not stopping, so i wanted to stop it from executing the function that writes numbers with a boolean.
It has to stop when leaving the button
Why does it not work?
And what are the alternatives?
You had a couple of issues. The 550ms delay on the timeout is causing the onmouseleave to fire before the code in debounce. Also your booli was being set in the wrong spot and was never being reset to true.
let counter;
let count = 0;
let booli = false;
window.onload = function() {
let x = document.getElementsByClassName('banana')
let i;
for (i = 0; i < x.length; i++) {
let y = x[i];
console.log(y);
x[i].onmousedown = debounce(function() {
start(y.className, y.value.replace(/\s/g, ''));
}, 1);//550
}
}
function debounce(a, b) {
return function() {
let timer;
clearTimeout(timer);
booli = true;
timer = setTimeout(function() {
if(booli)
{
a();
}
else
{
clearInterval(counter);
}
}, b);
};
}
function start(clicked_className, cha) {
counter = setInterval(function() {
add(clicked_className, cha);
count++;
}, 90);
}
function end() {
booli = false;
clearInterval(counter);
}
function add(clicked_className, cha) {
window.document.numeri.outpu.value =
window.document.numeri.outpu.value + cha;
}
#put{
width = 700px;
height: 18px;
font-size=14pt;
}
<!DOCTYPE html>
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
</head>
<body>
<form name="numeri">
<input type="text" id="put" name="outpu" style { width = 700px; height: 18px; font-size=14pt; }>
<input type="button" id="apple" class="banana" value=" 1 " onmouseleave="end()">
<input type="button" id="ada" class="banana" value=" 2 " onmouseleave="end()">
<input type="button" id="aded" class="banana" value=" 3 " onmouseleave="end()">
</form>
</body>
</html>
On why it doesn't work:
You have an issue with the way your events are behaving on your <input type="button">s.
For some reason, when you click a button, the onMouseLeave event is triggering, which is running end(). This, in turn, is setting booli to false, which is why it felt like something was wrong with your boolean.
You're also never setting booli to be true anywhere in the code you shared.
booli gets set to false before onMouseDown and start() never gets called.
I set booli as true in your declaration and threw a couple log statements into your code to show what I mean:
var counter;
var count = 0;
var booli = true;
console.log("booli=", booli);
window.onload = function() {
var x = document.getElementsByClassName('banana')
var i;
for (i = 0; i < x.length; i++) {
let y = x[i];
x[i].onmousedown = debounce(function() {
console.log("onMouseDown, booli is", booli);
if(booli) {
start(y.className, y.value.replace(/\s/g, ''));
}
}, 550);
};
}
function debounce(a, b) {
return function() {
var timer;
clearTimeout(timer);
timer = setTimeout(function() {
a();
}, b);
};
}
function start(clicked_className, cha) {
counter = setInterval(function() {
add(clicked_className, cha);
count++;
}, 90);
}
function end() {
console.log("onMouseLeave, setting booli=false");
booli=false;
clearInterval(counter);
}
function add(clicked_className, cha) {
window.document.numeri.outpu.value =
window.document.numeri.outpu.value + cha;
}
#put {
width: 700px;
height: 18px;
font-size=14pt;
}
<!DOCTYPE html>
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
</head>
<body>
<form name="numeri">
<input type="text" id="put" name="outpu">
<input type="button" id="apple" class="banana" value=" 1 " onmouseleave="end()">
<input type="button" id="ada" class="banana" value=" 2 " onmouseleave="end()">
<input type="button" id="aded" class="banana" value=" 3 " onmouseleave="end()">
</form>
</body>
</html>

How to end/clear/terminate a function starting after interval BEFORE the interval is over?

<!DOCTYPE html>
<html onmouseup="end()">
<head>
<meta charset="UTF-8">
</head>
<script>
var counter;
var count = 0;
window.onload=function()
{
var x=document.getElementsByClassName('banana')
var i;
for (i = 0; i < x.length; i++)
{
let y=x[i]; //////////hier funktioniert es nicht mit var !!!
console.log(y);
x[i].onmousedown = debounce(function()
{
start(y.className,y.value.replace(/\s/g, ''));
}, 550);
}
}
function debounce(a, b)
{
var timer;
return function()
{
clearTimeout(timer);
timer = setTimeout(function()
{
a();
}, b);
};
}
function start(clicked_className,cha)
{
counter = setInterval(function()
{
add(clicked_className,cha);
count++;
},90);
}
function end()
{
clearInterval(counter);
}
function add(clicked_className,cha)
{
window.document.numeri.outpu.value =
window.document.numeri.outpu.value + cha;
}
</script>
<style>
#put
{
width:700px;
height:18px;
font-size=14pt;
}
</style>
<body>
<form name="numeri">
<input type="text" id="put"name="outpu">
<input type="button"id="apple"class="banana"value=" 1 "onmouseleave="end()">
<input type="button"id="ada"class="banana"value=" 2 "onmouseleave="end()">
<input type="button"id="aded"class="banana"value=" 3 "onmouseleave="end()">
</form>
</body>
</html>
It starts after an Interval, but doesnt clear the interval if the conditions for terminating/clearing are met before the interval even started.
Now its like this:
Press button->550ms Waiting time->function->termination if conditions met
But it has to work like this too:
Press button->550ms Waiting time->termination if conditions met->no function
I have no idea how to fix that please help me :(
Also maybe is there a better way to do it in the first place?

JS: Slideshow inaccurate result

Hi I write this simple javascript slideshow cause I want to write my own slideshow in javascript. It automatically change the images by a set time interval. But when I try to click the backward and forward function the result is not accurate or the images are in order.
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = 0;
var count = images.length;
function slidingImages()
{
i = i % count;
document.banner.src = images[i];
i++;
}
function forward()
{
i = (i + 1) % count;
document.banner.src=images[i];
}
function backward()
{
if (i <= 0)
{
i = count - 1;
}
else
{
i--;
}
document.banner.src=images[i];
}
window.onload = function()
{
slidingImages(),setInterval(slidingImages, 3000)
};
<center>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<input type="button" value="«prev" onClick="backward()">
<input type="button" value="next»" onClick="forward()">
</center>
What is the solution so my slideshow would be accurate?
This will pause the automatic behavior when the mouse is within the red rectangle and continue in auto mode once the mouse is out of the red rectangle. The buttons of course work as expected.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
fieldset { width: -moz-fit-content; width: -webkit-fit-content; width: fit-content; border: 1px solid red; }
</style>
</head>
<body>
<section>
<p>
<img src="images/1.jpg" name="banner" id="name"/>
</p>
<fieldset id="control">
<input id="prev" type="button" value="◄">
<input id="next" type="button" value="►">
</fieldset>
</section>
<script>
var images = ["http://i1214.photobucket.com/albums/cc487/myelstery/1.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/2.jpg","http://i1214.photobucket.com/albums/cc487/myelstery/3.jpg"];
var i = -1;
var count = images.length;
var prev = document.getElementById('prev');
var next = document.getElementById('next');
var control = document.getElementById('control');
var autoSlide;
window.onload = auto;
function auto() {
autoSlide = setInterval(fwd, 3000) };
function pause() {
clearInterval(autoSlide);
}
function fwd() {
if (i >= 0 && i < 2)
{
i += 1;
}
else
{
i = 0;
}
document.banner.src=images[i];
}
function rev() {
if (i > 0 && i <= 2)
{
i -= 1;
}
else
{
i = 2;
}
document.banner.src=images[i];
}
prev.addEventListener('click', function() {
rev();
}, false);
next.addEventListener('click', function() {
fwd();
}, false);
control.addEventListener('mouseover', function() {
pause();
}, false);
control.addEventListener('mouseout', function() {
auto();
}, false);
</script>
</body>
</html>

How can i put image into the <div id="item1"></div>?

I am facing this problem.. May i know, how can i put image into this element tag,
<div id="item1"></div>
The purpose of this code below, is when the user click "+" the image will appear. And When the user click "play" button, the image that appeared, is supposed to put into the tag as mentioned above.
Unfortunately, i am not able to make the image that just appear, to be put into the tag..
I know there is hardcoding method, but sorry, i am not looking for this method..
<!DOCTYPE html>
<html>
<head>
<script src="code.jquery.com/jquery-1.7.2.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
.myClass {
width: 40px; height: 40px; float:left;
padding: 1px; margin:3px; position:absolute;
left:50px; top:60px; background:blue; color:white;
}
</style>
</head>
<body bgcolor="green";>
<div id="item1" class="myClass">F1</div>
<div id="item2" class="myClass">F2</div>
<div id="item3" class="myClass">F3</div>
<script>
var predator;
var Predatorlist = [];
function addvalue()
{
Predatorlist.push(uniqueid)
alert(Predatorlist);
}
function removevalue()
{
Predatorlist.pop(uniqueid)
alert(x.innerHTML=Predatorlist);
}
//************** End of Array ***********************
function Add() {
var id = Math.floor(Math.random()*101+1);
x = Math.random() * 550;
y = Math.random() * 250;
if (document.getElementById('amount').value < 50){
document.getElementById('amount').value++;
svg = document.getElementById("main");
var id = 'predator';
uniqueid = "frog" + document.getElementById('amount').value;
//namespaces for SVG
svgNS="http://www.w3.org/2000/svg";
xlinkNS="http://www.w3.org/1999/xlink";
// create a image element
image = document.createElementNS(svgNS, 'image');
// set id and other attributes
image.setAttributeNS(null, "id", uniqueid);
image.setAttributeNS(xlinkNS, "href","jef-frog.gif");
image.setAttributeNS(null, "x", x);
image.setAttributeNS(null, "y", y);
image.setAttributeNS(null, "width", "50");
image.setAttributeNS(null, "height", "50");
// append to svg
svg.appendChild(image);
} else {
alert("we got 50");
}
}
function Remove() {
if(document.getElementById('amount').value > 0)
{
document.getElementById('amount').value--;
svg = document.getElementById("main");
svg.removeChild(svg.lastChild);
}
}
function numinput(e){
// get the input value if enter
key=e.keyCode || e.which;
if (key==13){
total = document.getElementById("amount").value;
dummy = total;
// clear svg with image to avoid clearing the canvas
svg = document.getElementById("main");
element = svg.getElementsByTagName("image");
while(element.length>0){
element = svg.getElementsByTagName("image");
element[0].parentNode.removeChild(element[0]);
}
// use the input to create the number of frog.
while (dummy>0)
{
Add();
dummy--;
}
document.getElementById("amount").value = total;
}
}
function randomRange(min,max) {
return Math.random() * (max-min) + min;
}
/* Generate some random starting position */
var startItem1X = randomRange(50,100);
var startItem1Y = randomRange(50,100);
var startItem2X = randomRange(50,100);
var startItem2Y = randomRange(50,100);
var startItem3X = randomRange(50,100);
var startItem3Y = randomRange(50,100);
var startmyClassX = randomRange(50,100);
var startmyClassY = randomRange(50,100);
var item1 = $("#item1"),cycle1;
var item2 = $("#item2"),cycle1;
var item3 = $("#item3"),cycle1;
function runItem1() {
/* Set a the starting position to be random by editing the css */
$("#item1").css("left", startItem1X+"px");
$("#item1").css("top", startItem1Y+"px");
/* Cycle1 and Cycle2 variables allow infinite loop */
(cycle1 = function() {
var m = randomRange(50,100);
var n = randomRange(75,150);
item1.appendChild(image)
item1.animate({left:'+='+n},2000);
item1.animate({left:'+='+m, top:'+='+m}, 2000)
item1.animate({left:'-='+m, top:'+='+m}, 2000)
item1.animate({left:'-='+n},2000);
item1.animate({top:'-='+n},2000,cycle1)
})();
}
function runItem2() {
$("#item2").css("left", startItem2X+"px");
$("#item2").css("top", startItem2Y+"px");
(cycle2 = function() {
var m = randomRange(50,100);
var n = randomRange(75,150);
item2.animate({top:'+='+m, left:'+='+n},2000);
item2.animate({left:'-='+n},2000);
item2.animate({left:'+='+n, top:'-='+n},2000);
item2.animate({left:'-='+n},2000)
item2.animate({top:'+='+m},2000,cycle2)
})();
}
runItem1();
runItem2();
</script>
<SVG xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" id="main" style="border:inset 1px #000000;width:600;height:300"><param name='wmode' value='transparent'/></SVG>
<img src="jef-frog.gif" alt="frogsonice.com" width="100" height="100"/><BR/>
<INPUT type="button" value="+" onClick="Add(); addvalue();">
<INPUT type="text" id="amount" value=0 maxlength="3" size="1" onkeypress="numinput(evt)">
<INPUT type="button" value="-" onClick="Remove(); removevalue();">
<INPUT type="button" value="Play" onClick="runItem1(); runItem2();">
</body>
</html>
Many thanks to whoever out there, taking time to read and trying to help.. Thanks again..
would do it.
$('#your-play-button').click(function(e) {
$('#item1').html('<img src="mygif.gif" />');
});
edit after looking into your code you could replace:
document.getElementById('amount')
by $("#amount") etc. and really work with jQuery. Because now you don't use the advantage of jQuery, but you are just writing plain javascript...
well you can add a img tag using the innerhtml property or creating the element and appending it to div. then based on your logic you can set the tag's src of the image to the desired one.

Categories

Resources