Javascript execute a function after some time elapse - javascript

I am making a javascript based life game, and I am currently working on a salary system so, for example, every 10 seconds the balance goes up by 1. I've been looking for a while how to do it but never found anything. Here are my codes:
var balance = 100;
function balanceSys(){
let newbalance = balance + 100;
balance = newbalance;
document.getElementById("balance").innerHTML = (balance);
}
function salary(){
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Life Game</title>
<link rel="stylesheet" href="main.css">
<link href="https://fonts.googleapis.com/css?family=Mukta+Malar" rel="stylesheet">
</head>
<script src="main.js"></script>
<body>
<center><h1 class="title">Life Game</h1></center>
<table>
<tr>
<td class="mainTd"><h1 id="balance">0</h1></td>
<td class="mainTd"><h1 id="state">Begger</h1></td>
</tr>
</table>
<button onclick="balanceSys()">Click Me</button>
</body>
</html>

Use setInterval(). It will execute a function every X milliseconds (The second parameter).
You can also take in a parameter for amt to adjust by, and add varying amounts (In this case, I specified 1 in the original interval function, and 100 by default if not specified.
var balance = 0;
setInterval(() => balanceSys(1), 1000);
function balanceSys(amt = 100){
let newbalance = balance + amt;
balance = newbalance;
document.getElementById("balance").innerHTML = (balance);
}
function salary(){
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Life Game</title>
<link rel="stylesheet" href="main.css">
<link href="https://fonts.googleapis.com/css?family=Mukta+Malar" rel="stylesheet">
</head>
<script src="main.js"></script>
<body>
<center><h1 class="title">Life Game</h1></center>
<table>
<tr>
<td class="mainTd"><h1 id="balance">0</h1></td>
<td class="mainTd"><h1 id="state">Begger</h1></td>
</tr>
</table>
<button onclick="balanceSys()">Click Me</button>
</body>
</html>

I agree with FrankerZ's method, but you don't want to run getElementById every second. Here is a better solution. DOM manipulation is very slow, so try to minimize the impact in performance as much as possible.
function balanceSys(){
let element = document.getElementById("balance");
setInterval(() => {
let newbalance = balance + 1;
balance = newbalance;
element.innerHTML = (balance);
}, 10000);
}

Related

Javascript textarea charcoutner isn't working

hello my code isn't working idk why i tried to make textarea char counter that only shows the chachter not maxiumum
here is the java script
let text = document.querySelector('#text');
let number = text.value.length;
let count = document.querySelector('#count');
text.addEventListener("input", updateCount());
function updateCount(){
count.value + number
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Karakter sayısı</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="ses">
<textarea id="text" placeholder="Yazıyı buraya Kopyala veya Yaz"></textarea>
</div>
<span id="filhu">Bu kadar yazdın:</span><span id="count">0</span>
<script src="main.js"></script>
</body>
</html>
In your text.addEventListener("input", updateCount()); assignment you did not assign the function updateCount to the input event of the selected element but instead you executed it once and assigned the non-existent return value of the function call to the event.
And in the function itself you will need to put (=assign) the calculated count somewhere too:
let text = document.querySelector('#text');
let count = document.querySelector('#count');
text.addEventListener("input", updateCount);
function updateCount(ev){
count.textContent=ev.target.value.length;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Karakter sayısı</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="ses">
<textarea id="text" placeholder="Yazıyı buraya Kopyala veya Yaz"></textarea>
</div>
<span id="filhu">Bu kadar yazdın:</span><span id="count">0</span>
<script src="main.js"></script>
</body>
</html>
ev.target.value.length gets the current length of the <textarea> element and count.textContent= assigns it to the target <span>.
A better way is by subscribing to the keyup event and getting the value from the scope using this keyword
function characterCount() {
document.getElementById('text').onkeyup = function () {
document.getElementById('count').innerHTML = this.value.length;
};
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Karakter sayısı</title>
</head>
<body>
<div class="ses">
<textarea id="text" placeholder="Yazıyı buraya Kopyala veya Yaz" onchange="characterCount()"></textarea>
</div>
<span id="filhu">Bu kadar yazdın:</span><span id="count">0</span>
</body>
</html>

Making options from 0 to 100 with javascript

I need to make section with options in it going from 0 to 100 when the page is open, in html is simple just type it all out :D, but i think i can do this in java script but i am not quite sure how.
Here is my html and a little bit of js code:
function options() {
var section = document.getElementById("section");
for(var i = 0;i < 100;i++){
section.innerHTML = "<option value="i">"+i+"</option>";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<section id="section" onload="options">
</section>
</body>
</html>
Here's How you can do it -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<select id="mySelect" onload="options()"></select>
</html>
<script type="text/javascript">
var selectElem = document.getElementById("mySelect");
for (var i = 0; i < 100; i++){
var element = document.createElement("option");
element.innerText = i + 1;
selectElem.append(element);
}
</script>
Here's the working example
<section> tag doesn't support onload.
You can check w3schools onload event and MDN: onload, the tags support onload are: <body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>
So you can move onload="options()" to <body> then escape the double quotes and use <select> instead of <section> as the comments mentioned.
function options() {
var section = document.getElementById("section");
for(var i = 0;i < 100;i++){
section.innerHTML += "<option value=\"i\">"+i+"</option>";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body onload="options()">
<select id="section">
</select>
</body>
</html>

Code to compute collatz conjecture has no output

So, I saw a video by Veritasium -> (https://youtu.be/094y1Z2wpJg)
And I wanted to try to translate it into code.
when I run it, nothing gets logged and no errors appear at all
it might be a very simple fix due to the fact that I am a VERY new programmer so yea.
if you could help that would be great! :)
var i = document.getElementById("solvebtn");
function solve() {
while(i > 1) {
//even
if(i % 2 == 0) {
(i / 2)
console.log(i)
}
//odd
else {
(i * 3 + 1)
console.log(i)
}
}
}
/* RULES */
//if odd i * 3 + 1
//if even i / 2
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3X + 1</title>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" placeholder="Number"></input>
<button id="solvebtn" onclick="solve()">Solve</button>
</body>
</html>
You where using the wrong value, the button doesnt contain the input value, you need to get that from the input field.
var i = document.getElementById("solvebtn");
function solve() {
let value = document.getElementById("val").value;
while (value > 1) {
//even
if (value % 2 == 0) {
value = value / 2
console.log(value)
}
//odd
else {
value = value * 3 + 1
console.log(value)
}
}
}
/* RULES */
//if odd i * 3 + 1
//if even i / 2
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3X + 1</title>
<script src="app.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<input type="text" id="val" placeholder="Number"></input>
<button id="solvebtn" onclick="solve()">Solve</button>
</body>
</html>
you should change the input type to number in your HTML code
you can get the input number using element.value
const element = document.getElementById("input");
function solve() {
//this is wat you shold add
let i = element.value;
console.log(i);
while(i > 1) {
//even
console.log("ddd")
if((i % 2) === 0) {
(i /= 2)
console.log(i)
}
//odd
else {
(i =i*3 + 1)
console.log(i)
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="#">
<title>Document</title>
<script defer src="app.js"></script>
</head>
<body>
<!--change the type to number-->
<input id="input" type="number" placeholder="Number"></input>
<button id="solvebtn" onclick="solve()">Solve</button>
</body>
</body>
</html>

SetInterval Not Working Each time a Button Is Clicked

I have an H1 value that should decrease each time a button is clicked. The value of H1 is 10, when clicked the first time, it reduces to 9 after two seconds and when clicked again, it reduces to 8 after 2 seconds also. And it continues like that. My code below is not working as expected. It starts reducing only after the first clicks until it gets to zero. Please help me check my code below and tell me what I'm doing wrong.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>10</h1>
<button onclick='execute()'>Start Timer</button>
</body>
<script>
let count = document.getElementsByTagName("h1")[0].innerHTML;
let btn = document.getElementsByTagName("button")[0]
function execute(){
window.setInterval(function()
{
count--;
h1 = document.getElementsByTagName("h1")[0].innerHTML = count;
if(count <= 0){
document.getElementsByTagName("h1")[0].innerHTML = 0
btn.disabled = true;
}
}, 1000);
}
</script>
</html>
You have to use setTimeout instead, because with setInterval it runs on a loop. If you want 2 seconds you have to use 2000 ms also.
Here it goes what you want:
let count = document.getElementsByTagName("h1")[0].innerHTML;
let btn = document.getElementsByTagName("button")[0]
function execute(){
window.setTimeout(function() {
count--;
h1 = document.getElementsByTagName("h1")[0].innerHTML = count;
if(count <= 0){
document.getElementsByTagName("h1")[0].innerHTML = 0
btn.disabled = true;
}
}, 2000);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>10</h1>
<button onclick='execute()'>Start Timer</button>
</body>
</html>

Phrase Element p is null even though it's having a value [duplicate]

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
Basically I want to rephrase a <p> block but the element is null even though I gave it a value. Because of that I can't change the value of it. The weird thing about it, in some other code of mine the exact same thing worked out. Would be nice if someone could explain me my error.
For the understanding of the code. I wrote a quicksort and wanted to show the sorted array. I'm trying to grab my HTML box via the getElementById() Method.
The following code is necessary to know.
const textEl = document.getElementById("test");
function sort(array, low = 0, high = array.length - 1){
let index;
if (array.length > 1){
index = partition(array ,low, high);
if (low < index - 1){
sort(array, low, high - 1);
}
if (index < high){
sort(array, index, high);
}
}
textEl.innerHTML = array;
return array;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="quicksort.js"></script>
</head>
<body>
<div class="div-1">
<p class="array-el" id="test">Test</p>
</div>
</body>
</html>
It is because you are running your javascript before the HTML loads. Put the script at the end of the body tag like so:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="div-1">
<p class="array-el" id="test">Test</p>
</div>
<script src="quicksort.js"></script>
</body>
</html>

Categories

Resources