I have a little game, I want to set a timer for it for 1 second, yet I keep failing.
The timer makes the balance randomly jump from 0 to 13000 + some change.
<script>
var satoshi = 0; var hash = 1;
</script>
<center>
<h4>
Hashs Per Second:
<script type="text/javascript">
document.write(hash)
</script>
</h4>
</center>
<center>
<p id="cookiespersecond">Satoshis: 0</p>
</center>
<button onclick="minebtc()"><img src="kop.png" height=28 width=32>Mine BTC</button>
<button onclick="stop()"><img src="kop.png" height=28 width=32>Stop Mining BTC</button>
<script>
function minebtc() {
satoshi = satoshi + hash
update()
}
function update() {
document.getElementById('cookiespersecond').innerHTML = "Satoshis: " + satoshi;
setTimeout(update, 3000)
minebtc()
}
function stop() {
}
</script>
Your RangeError is caused by minebtc calling update and that one calling minebtc over and over again, without letting the code finish running (therefore allowing for other stuff to be inserted in the event loop). To fix this, you can simply call minebtc with a 0ms timer, this basically allows for other events to interleave their code between your mutual recursion.
<script>
var satoshi = 0; var hash = 1;
</script>
<center>
<h4>
Hashs Per Second:
<script type="text/javascript">
document.write(hash)
</script>
</h4>
</center>
<center>
<p id="cookiespersecond">Satoshis: 0</p>
</center>
<button onclick="minebtc()"><img src="kop.png" height=28 width=32>Mine BTC</button>
<button onclick="stop()"><img src="kop.png" height=28 width=32>Stop Mining BTC</button>
<script>
function minebtc() {
satoshi = satoshi + hash;
setTimeout(update, 3000);
}
function update() {
document.getElementById('cookiespersecond').innerHTML = "Satoshis: " + satoshi;
setTimeout(minebtc, 0)
}
function stop() {
}
</script>
Related
My script is working well, but the only problem i have.
i want to show the counter in human readable style, becouse now its showing in milliseconds
i want like time left is 1:02 Minutes
so i want to display time left in readable style in browser not milliseconds
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<p>Time left: <span id="timr"></span></p>
<p id="hpd">Welcome here john</p>
<p id="shp" style="display:none">Your time is up</p>
<input type="button" value="Hi john" id="btn">
<script>
var SessionTime=100000;
var tickDuration=1000;
var myInterval=setInterval(function(){
SessionTime=SessionTime-tickDuration
$("#timr").text(SessionTime);
},1000);
var myTimeOut=setTimeout(SessionExpireEvent,SessionTime);
$("input").click(function(){
clearTimeout(myTimeOut);
SessionTime=100000;
myTimeOut=setTimeout(SessionExpireEvent,SessionTime);
});
function SessionExpireEvent()
{ clearInterval(myInterval);
$("#btn").attr("disabled", true);
$("#hpd").hide();
$("#shp").show();
}
</script>
</body>
</html>
You can simply replace
$("#timr").text(SessionTime);
with
$("#timr").text(`${Math.floor(SessionTime/60000)}:${SessionTime/1000%60}`);
However, your code can be simpler if you don't need to know how much time is left to milliseconds precision.
setInterval and setTimeout are the only functions in your code that need their arguments in milliseconds.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<p>Time left: <span id="timr"></span></p>
<p id="hpd">Welcome here john</p>
<p id="shp" style="display:none">Your time is up</p>
<input type="button" value="Hi john" id="btn">
<script>
var SessionTimeInSec = 40;
var myInterval = setInterval(function() {
SessionTimeInSec--;
$("#timr").text(`${Math.floor(SessionTimeInSec/60)}:${SessionTimeInSec%60}`);
}, 1000);
var myTimeOut = setTimeout(SessionExpireEvent, SessionTimeInSec*1000);
$("input").click(function() {
clearTimeout(myTimeOut);
SessionTimeInSec = 40;
myTimeOut = setTimeout(SessionExpireEvent, SessionTimeInSec*1000);
});
function SessionExpireEvent() {
clearInterval(myInterval);
$("#btn").attr("disabled", true);
$("#hpd").hide();
$("#shp").show();
}
</script>
</body>
</html>
I did the following changes:
Change SessionTime to SessionTimeInSec and divide numbers by 1000.
Multiple SessionTimeInSec by 1000 for the arguments passed to both funtions setInterval and setTimeout.
Get rid of tickDuration since it will equal to one. Consonantly, change SessionTime = SessionTime - tickDuration to SessionTimeInSec--.
Change $(#timr) text to 0:0 in SessionExpireEvent()
Seems like you want something like this:
var mins = Math.floor(SessionTime / 1000 / 60);
SessionTime %= 60000;
var secs = SessionTime / 1000;
$("#timr").text(mins + ":" + secs);
AddEventListener won't work when I clicked the button, the class name is exact on the html.
And how to properly set the time interval. I want the ball rolling and stop on the given time example 10s.
This is the html file and below is the js code
<!DOCTYPE html>
<html>
<link rel ='stylesheet' href ="style.css">
<script src = 'main.js'></script>
<body>
<div class = "wrapper_main" align ='center'>
<div > This is a lotto app design sample
<div class="ball-size">
<img src = "numbers/ball-0.png" class = "balls-0">
<img src = "numbers/ball-0.png" class = "balls-1">
<img src = "numbers/ball-0.png" class = "balls-2">
</div>
<div onclick="myFunction()" class ="buttons">
<button class = "btn-roll"> Roll </button>
</div>
</div>
</div>
</body>
</html>
js file ----
document.querySelector(".btn-roll").addEventListener("click", myFunction);
/*
var timesRun = 0;
var interval = setInterval(myFunction, 0);
timesRun += 1;
if(timesRun ===10) {
clearInterval(interval);
} */
function myFunction() {
var balls, balls1, balls2;
balls = Math.floor(Math.random() * 10);
balls1 = Math.floor(Math.random() * 10);
balls2 = Math.floor(Math.random() * 10);
var ballsDOM = document.querySelector(".balls-0");
var ballsDOM1 = document.querySelector(".balls-1");
var ballsDOM2 = document.querySelector(".balls-2");
ballsDOM.src = "numbers/ball-" + balls + ".png";
ballsDOM1.src = "numbers/ball-" + balls + ".png";
ballsDOM2.src = "numbers/ball-" + balls + ".png";
console.log("done");
}
It is important to do the event biding, after the DOM is created and the button exists in the page.
For example this won't work:
<body>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
Because we binded an event on a button that is not exists yet. but:
<body>
<button class="btn-roll">click on me</button>
<script>
document.querySelector('.btn-roll').addEventListener('click', myFunction);
function myFunction(){
alert(1);
}
</script>
</body>
Will work fine.
You can use libraries like jQuery to ensure the DOM is ready like this:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
document.querySelector('.btn-roll').addEventListener('click', myFunction);
// or:
// $('.btn-roll').on('click',myFunction);
})
function myFunction(){
alert(1);
}
</script>
<button class="btn-roll">click on me</button>
</body>
I have an assignment that requires me to code a website using HTML and JavaScript. The Website is just a very basic website (I'm a Computer Science Student just starting HTML) about the planet in the solar system.
The website includes two buttons, as you'll see in the below code, that change the text on the screen to the next planet in the solar system however sometimes when the buttons are clicked this doesn't occur, instead the text changes to the incorrect planet or simply states "undefined" until the button is clicked a few more times when the website will continue to work correctly.
Here's my code:
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i =0;
function nextplanet(){
if (i<endofplanets){
document.getElementById('p1').innerHTML=planets[i];
i++;
}
}
</script>
<script>
function previousplanet(){
if (i>-1){
document.getElementById('p1').innerHTML=planets[i];
i--;
}
}
</script>
<p id="p1">---</p>
<button type="button" onclick=nextplanet()>Next Planet</button>
<button type="button" onclick=previousplanet()>Previous Planet</button>
</body>
</html>
Any help with this would be much appreciated
Try this.. simple solution
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i = -1;
function nextplanet()
{
i=i+1;
if(i==endofplanets){
i=0;
}
document.getElementById('p1').innerHTML=planets[i];
}
function previousplanet(){
i=i-1;
if(i<0){
i=endofplanets-1;}
document.getElementById('p1').innerHTML=planets[i];
}
</script>
<p id="p1">---</p>
<button type="button" onclick="nextplanet()">Next Planet</button>
<button type="button" onclick="previousplanet()">Previous Planet</button>
</body>
</html>
check this:- you need to add else condition in next button and reset i value to 0, this is fiddle https://jsfiddle.net/3bsyypL9/2/
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i =0;
function nextplanet(){
if (i<endofplanets){
document.getElementById('p1').innerHTML=planets[i];
i++;
}
else
{
i = 0;
document.getElementById('p1').innerHTML=planets[i];
i++;
}
}
</script>
<script>
function previousplanet(){
if (i>0){
i--;
document.getElementById('p1').innerHTML=planets[i];
}
}
</script>
<p id="p1">---</p>
<button type="button" onclick="nextplanet()">Next Planet</button>
<button type="button" onclick="previousplanet()">Previous Planet</button>
</body>
</html>
The answer of DHRUV GUPTA contain an error, when i equals 7, if you do nextplanet() then i is increased by one. So if you trigger the function previousplanet(), i is equal to 8 and you get an undefined result.
The simplest way to avoid this error is to not increase i everytime.
Check this :
http://codepen.io/anon/pen/EZbBVX
NO LOOP VERSION
i = -1; //To be sure that the first planet will be Mercury
function nextplanet(){
if (i<endofplanets){
i = Math.min(i+1,endofplanets-1); //Take the minimum between i+1 and last indice of your array (7), so i will ever be lower of equal to the max indice of your array
document.getElementById('p1').innerHTML=planets[i];
}
}
function previousplanet(){
if (i>-1){
i = Math.max(i-1,0); //The same, i will be ever greater or equal to 0, which is the lower indice of your array ;)
document.getElementById('p1').innerHTML=planets[i];
}
}
LOOP VERSION
i = 0;
function nextplanet(){
document.getElementById('p1').innerHTML=planets[i];
i = (i+1) % endofplanets; //With a modulo, your indice is always between 0 and endofplanets-1, google modulo if you don't know this operator ;)
}
function previousplanet(){
document.getElementById('p1').innerHTML=planets[i];
i = (i-1) % endofplanets;
}
Hi this is my first javascript and it is not working. The script is programmed to display a clock. The code is as follows:
<html>
<head>
<script type="text/javascript" src="clock.js" > </script>
</head>
<body onload=display_ct();>
<span id='ct' ></span>
</body>
</html>
The javascript is :
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var strcount
var x = new Date()
document.getElementById('ct').innerHTML = x;
tt=display_c();
}
When execute I get a blank screen. What and where is the mistake ?
TIA :)
You should probably be consistent with ending lines in semi-colon. Also, you should check that clock.js is loading; finally put the onload handler in quotes like
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
tt = display_c();
}
<html>
<body onload="display_ct();">
<span id='ct'></span>
</body>
</html>
Please enclose your onload attribute value of body tag inside " " .
It should be
<body onload="display_ct();">
Try using setInterval(), also this line won't work in some browsers:
setTimeout('display_ct()',refresh)
var ct;
function display_c() {
//timer block
setInterval(function() {
ct.innerHTML = new Date().toString();
}, 1000); //execute every 1 second
}
function display_ct() {
ct = document.getElementById('ct'); //initialize once.
display_c();
}
<!-- onload, enclosed in quotes -->
<body onload="display_ct()">
<span id='ct'>Loading ...</span>
</body>
You made two errors when entering the display_ct function. You needed to wrap the <body>'s onload event with quotes, and remove the quotes and the parentheses on the setTimeout. See below.
function display_c() {
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout(display_ct, refresh);
}
function display_ct() {
var x = new Date();
document.getElementById('ct').innerHTML = x;
display_c();
}
<html>
<head>
<script type="text/javascript" src="clock.js">
</script>
</head>
<body onload="display_ct()">
<span id='ct'></span>
</body>
</html>
I made a simple timer in javascript using a for loop, but upon clicking the button to call the function test(), the whole page freezes up so I assume I have an infinite loop somewhere
This is my code:
<html>
<head>
<script>
function test() {
var HowLong = 5;
for (var i=0;i<HowLong;i--) {
document.write(HowLong[i] + "<br>");
}
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="Start Timer">
</body>
</html>
Yes you have infinite loop problem in the for loop:
for (var i=0;i<HowLong;i--)
Instead of i-- try i++
for (var i=0;i<HowLong;i++)
One more thing HowLong is not an array so you can't use HowLong[i], just simply use :
document.write(i+ "<br>");
As #jfriend00 has mentioned in comments When you use document.write() after the document is loaded, it will clear the current document and start a new one. In your case your button Start Timer will be cleared. If you want to avoid it you can use div and add value to it.
<html>
<head>
<script>
function test() {
var HowLong = 5;
for(var i=0;i<HowLong;i++) {
document.getElementById("myDiv").innerHTML += i + "<br>";
}
}
</script>
</head>
<body>
<input type="button" onclick="test()" value="Start Timer">
<div id="myDiv"></div>
</body>
</html>
Try this;
for (var i=0;i<HowLong;i++) {
document.write(i + "<br>");
}
<html>
<head>
<script>
var HowLong = 5;
var isRun = false;
function mf(i){
document.getElementById('myAnchor').innerHTML = i;
}
function rt(i)
{
setTimeout(function(){
mf(i++);
if(i!=HowLong+1)rt(i);
else isRun = false;
}, 1000); // 1000ms = 1sec
}
function test() {
var i = 1;
if(!isRun)
{
isRun = true;
rt(i);
}
}
</script>
</head>
<body>
<div id="myAnchor"></div>
<input type="button" onclick="test()" value="Start Timer">
</body>
</html>
you forget to add delay in your loop