Code execution speed is slower and slower in time - javascript

In my project I need to see sensors data in textarea window
and after some time to save those data in txt file.
I use this code :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
var updateInterval = 50;
var updateChart = function(count) {
count = count || 1;
Val1 = Math.floor((Math.random() * 100) + 1);
Val2 = Math.floor((Math.random() * 100) + 1);
Val3 = Math.floor((Math.random() * 100) + 1);
$(document).ready(function() {
var $textarea = $('textarea');
$textarea.scrollTop($textarea[0].scrollHeight);
});
var d = new Date();
$("#output").append(document.createTextNode(d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " - , " + Val1 + ", " + Val2 + ", " + Val3 + "\n"));
}
setInterval(function() {
updateChart()
}, updateInterval);
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
pom.style.display = 'none';
document.body.appendChild(pom);
pom.click();
document.body.removeChild(pom);
}
</script>
</head>
<body>
<form onsubmit="download(this['name'].value, this['text'].value)">
Filename: <input type="text" name="name" value=" .txt">
<textarea id='output' cols="40" rows="10" name="text" style="border:solid 2px blue;">
Time ,Val1, Val2, Val3
</textarea>
<input type="submit" value="SAVE">
</form>
</body>
</html>`
The problem is in the fact: my code execution speed is slower and slower if time
between start and file saving moment is longer !
If I use 20 samples/sec this amount of slowdown is not acceptable.
Is it possible to get faster code and much less dependent of time (txt file size) ?

Related

My internal JavaScript for my Kelvin/Fahrenheit Converter is not working

I put my JavaScript inside tags instead of externally(because external files weren't working) and for some reason my code is not running.
Just to be sure that it wasn't a problem with the code itself, I put a simple alert before all the code and nothing popped up.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fahrenheit/Kelvin Converter</h1>
<div id = "first" class = "oneof">
<h2>Kelvin to Fahrenheit</h2>
<input type = "text" placeholder = "Enter Kelvin here" id = "kinput">
<button id = "ksubmit">Submit Kelvin</button><br><br>
<textarea id = "fpopup" rows = "5" cols = "50"></textarea>
</div>
<div id = "second" class = "oneof">
<h2>Fahrenheit to Kelvin</h2>
<input type = "text" placeholder = "Enter Fahrenheit here" id = "finput">
<button id = "fsubmit">Submit Fahrenheit</button><br><br>
<textarea id = "kpopup" rows = "5" cols = "50"></textarea>
</div>
<script>
alert("Hello World"); //Testing JS
if(6==6){
alert("ua");
}
function ftok(f){
k = (f − 32) * 5/9 + 273.15;
return k;
}
function ktof(k){
f = (K − 273.15) * 9/5 + 32;
return f;
}
document.getElementById("ksubmit").onclick = function() {
document.getElementById("fpopup").value = document.getElementById("kinput").value + " degrees Kelvin is " + ktof(Number(document.getElementById("kinput").value)) + " degrees Fahrenheit"
}
document.getElementById("fsubmit").onclick = function() {
document.getElementById("kpopup").value = document.getElementById("finput").value + " degrees Fahrenheit is " + ftok(Number(document.getElementById("finput").value)) + " degrees Kelvin"
}
</script>
</body>
</html>
You can use DOMContentLoaded function to make sure the HTML is ready and parsed properly. Also you have some syntax errors which i have fixed as well.
Also, You were using some weird minus and multiplication characters.
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed
Your code is now working as expected.
Live Demo:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Fahrenheit/Kelvin Converter</h1>
<div id="first" class="oneof">
<h2>Kelvin to Fahrenheit</h2>
<input type="text" placeholder="Enter Kelvin here" id="kinput">
<button id="ksubmit">Submit Kelvin</button><br><br>
<textarea id="fpopup" rows="5" cols="50"></textarea>
</div>
<div id="second" class="oneof">
<h2>Fahrenheit to Kelvin</h2>
<input type="text" placeholder="Enter Fahrenheit here" id="finput">
<button id="fsubmit">Submit Fahrenheit</button><br><br>
<textarea id="kpopup" rows="5" cols="50"></textarea>
</div>
<script>
window.addEventListener('DOMContentLoaded', (event) => {
if (6 == 6) {
alert("ua");
}
function ftok(f) {
var k = (f - 32) * 5 / 9 + 273.15;
return k;
}
function ktof(k) {
var f = (k - 273.15) * 9 / 5 + 32;
return f;
}
document.getElementById("ksubmit").onclick = function() {
document.getElementById("fpopup").value = document.getElementById("kinput").value + " degrees Kelvin is " + ktof(Number(document.getElementById("kinput").value)) + " degrees Fahrenheit"
}
document.getElementById("fsubmit").onclick = function() {
document.getElementById("kpopup").value = document.getElementById("finput").value + " degrees Fahrenheit is " + ftok(Number(document.getElementById("finput").value)) + " degrees Kelvin"
}
})
</script>
</body>
</html>

How can I stop my timer function if the quiz ends before time is up? Javascript

I have everything working as it should, except for me trying a million different things and not being able to get the timer function to stop counting down if the quiz ends before the 60 seconds is up.
//total score var that is defined in local storage and question number var that will be incremented later on
var totalScore = 0,
questionNumber = 0,
i = 0;
// questions object
allQuestions = [{
question: "What do you call a variable with multiple boolean values?",
choices: ["variable", "object", "array", "let"],
correctAnswer: "array"
},
{
question: "A useful tool for debugging during development is_______.",
choices: ["wrench", "Chrome dev tools", "Visual Studio Code", "keyboard"],
correctAnswer: "Chrome dev tools"
},
{
question: "Where will you find most of the answers to the questions you will have in your coding career?",
choices: ["Teachers", "Coworkers", "User manual", "The Internet"],
correctAnswer: "The Internet"
},
{
question: "What should you do when using git before you push a project to the repository?",
choices: ["pull", "bop it", "save it", "close it"],
correctAnswer: "pull"
}
];
var counterValue = 60;
var mainContent = $('#mainContent');
//logic if correct answer is chosen
function correctGuess() {
totalScore ++;
questionNumber ++;
var updatePage = question(questionNumber);
localStorage.setItem("scoreCount", totalScore);
$('#mainContent').html(updatePage);
if(questionNumber < 4){
var updatePage = question(questionNumber);
$('#mainContent').html(updatePage);
}
};
//logic if incorrect answer is chosen
function incorrectGuess() {
counterValue -= 5;
totalScore = 0;
questionNumber ++;
var updatePage = question(questionNumber);
$('#mainContent').html(updatePage);
};
//starting screen
function welcome() {
mainContent.html('<h2>Welcome to the Code Quiz!</h2>' + '<br />' +
'<h5>If you think you have what it takes, go ahead and click the start button to see how you do!</h5>'
+ '<button type="button" class="btn btn-primary" id="startQuizBtn">Start Quiz!</button>');
document.getElementById("startQuizBtn").addEventListener("click", function() {question(i)});
//timer function
document.getElementById("startQuizBtn").addEventListener("click", function() {timer()})
};
function timer() {
var timer = setInterval(function(){
counterValue -= 1;
$("#timer-value").html(counterValue)
if (counterValue <= 0) {
clearInterval(timer)
displayScore()
}
},1000)
}
//loads start page to begin with
window.onload = function () {
this.welcome();
};
//logic to run through questions object
function question(i) {
if (i < 4) {
mainContent.html('<div id="questionDiv">' +
'<h2>Question ' + (i + 1) + '<h2>' +
'<h3>' + allQuestions[i].question + '</h3>' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[0] + '" checked="yes">' + allQuestions[i].choices[0] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[1] + '">' + allQuestions[i].choices[1] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[2] + '">' + allQuestions[i].choices[2] + '</input>' + '<br />' +
'<input type="radio" class="radiobtn" name="questionChoices" value="' + allQuestions[i].choices[3] + '">' + allQuestions[i].choices[3] + '</input>' + '<br />' +
'<button type="button" class="btn btn-primary" id="submitButton">Submit</button>' + '</div>' );
} else {
chooseNextScreen();
};
//submit button at the bottom of the questions
$('#submitButton').on('click', function() {
if($('input:radio[name=questionChoices]:checked').val() === allQuestions[i].correctAnswer && i < 4) {
correctGuess();
} else {
incorrectGuess();
}
});
};
//logic to decide what screen to append next
function chooseNextScreen(){
if (questionNumber < 4) {
question();
} else {
displayScore();
}
};
// end screen of quiz
function displayScore() {
//Text, form and button on end page
$('#mainContent').html('<h2>Well Done!</h2>' + '<h4> You scored ' + totalScore + '!</h4>' + '<h4>Please enter your name for the end screen</h4>' +
'<hr />' + '<form>' + '<input class="form-control" id="initialsBox" type="text" placeholder="Your Name">' + '<button type="button" class="btn btn-primary" id="hiScoreSubmitBtn">Submit</button>' + '</form>');
// Submit button on end screen of quiz
$('#hiScoreSubmitBtn').on('click', function(event) {
localStorage.setItem(initialsBox[0].value, totalScore);
mainContent.html('<h1>' + initialsBox[0].value + ' scored a ' + totalScore + '!' + '</h1>');
});
var initialsBox = $("#initialsBox");
};
//calls function for quiz to run
question(questionNumber);
Here's the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Code Quiz</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
</head>
<body>
<!--Top row heading of title and time left-->
<div class="row">
<div class="col">
<h1 id="code-quiz">Code Quiz!</h1>
</div>
<div class="col">
<h3 id="timer">Time Left: <span id="timer-value"></span></h3>
</div>
</div>
<!--Main Content-->
<div class="container">
<div id="headingLine" class="row main-heading">
<div class="classname" id="id"></div>
</div>
<div class="row">
<div class="col" id="mainContent">
</div>
</div>
</div>
<!--Script Tags-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script src="assets/script.js"></script>
</body>
</html>
I cant help but feel like the answer is right in front of me, but I've been staring at it for hours at this point.
document.getElementById("startQuizBtn").addEventListener("click", ()=>{
var counterVal = 5;
timer=setInterval(function() {
counterVal=counterVal-1;
console.log(counterVal)
if(counterVal==0){
clearInterval(timer)
}
},1000)
})

sessionStorage displays undefined in IE11?

I am working on web related applications.When i try to display sessionStorage item it returns "undefined".
IE settings also changed but still i am getting same.
Login.html page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var currentDate = new Date,
dformat = [(currentDate.getMonth() + 1),
currentDate.getDate(),
currentDate.getFullYear()].join('/') +
' ' +
[currentDate.getHours(),
currentDate.getMinutes(),
currentDate.getSeconds()].join(':');
function unicsession(length) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
var sess = "";
for (var x = 0; x < length; x++) {
var i = Math.floor(Math.random() * chars.length);
sess += chars.charAt(i);
}
return sess;
}
function generate() {
var intime = dformat;
sessionStorage.setItem("logintime", intime);
var username = document.getElementById("Username").value;
sessionStorage.setItem("username", username);
var unisession = unicsession(5);
sessionStorage.setItem("unisession", unisession);
}
</script>
</head>
<body>
<table>
<tr>
<td>
<input id="Username" type="text" />
</td>
</tr>
<tr>
<td>
Click here
</td>
</tr>
</table>
</body>
</html>
home.htm page code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
var getid = sessionStorage.getItem("username");
var logintimes = sessionStorage.getItem("logintime");
var unicsessionid = sessionStorage.getItem("unisession");
var currentDate = new Date,
outformat = [(currentDate.getMonth() + 1),
currentDate.getDate(),
currentDate.getFullYear()].join('/') +
' ' +
[currentDate.getHours(),
currentDate.getMinutes(),
currentDate.getSeconds()].join(':');
function Getout() {
alert("Login Id: " + getid + " ; login Time: " + logintimes+" ; Unic Session-Id : "+unicsessionid+" ; Logout Time : "+outformat);
}
</script>
</head>
<body>
<input id="logout" type="button" value="Logout" onclick="Getout()"/>
</body>
</html>
When i click on login page it redirect to home page and after click on logout button in home page it displays undefined.
How can i resolve this issue.
Thanks in advance for help.
sessionStorage is not avialable from IE if you access your files via your local filesystem. Use any local server to serve your scripts as http

Performing a POST in window.open()

I'm trying to open a popup and I'd like to send data using the post method when it opens.
Can anyone help me.
I am getting "Uncaught syntax error. Unexpected token }"
function MapIt(){
var ListIds = selected_Listings.join();
if (navigator.appName == "Microsoft Internet Explorer") {
var opts = "screenX=0,screenY=0,width=" + screen.width + ",height=" + screen.height;
} else {
var opts = "outerWidth=" + screen.availWidth + ",outerHeight=" + screen.availHeight + ",screenX=0,screenY=0";
}
var urlStr = "http://www.dev.theabc.com/bingmaps/Map ";
$('<form action=' + urlStr + ' ' + ' target="submission" onsubmit="window.open("", "Map",' + opts + ' "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes");return true;" method="post"><input type="hidden" name="listid" value="' + ListIds + '"></form>').submit();
}
After knowing that you don't realy wanted a post.
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(function(){
MapIt = function() {
ListIds = '1234';//selected_Listings.join();
if (navigator.appName == "Microsoft Internet Explorer") {
var opts = "screenX=0,screenY=0,width=" + screen.width + ",height=" + screen.height;
} else {
var opts = "outerWidth=" + screen.availWidth + ",outerHeight=" + screen.availHeight + ",screenX=0,screenY=0";
}
$('#myHidden').val(ListIds);
window.open('opener.html','Map', opts+',toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no');
}
});
</script>
</head>
<body>
<button id="run" onclick="MapIt()">run</button>
<input type="hidden" id="myHidden">
</body>
</html>
An then in your opener.html
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(function(){
var listIds = window.opener.document.getElementById('myHidden').value;
$('#valuesRead').text(listIds);
});
</script>
</head>
<body>
<span id="valuesRead"></span>
</body>
</html>
BEWARE This has in some browsers (Chrome for one) security objections if you run it locally
Actually... your syntax is wrong in the form
It should look like this
$('<form action="'+urlStr+' target="submission" onsubmit="window.open(\'http://www.google.com\',\'Map\',\''+opts+',toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no\');return true;" method="post"><input type="hidden" value="'+ListIds+'"></form>').submit();
You have to escape the " inside the string... oh and a coma is missing after the opts...
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(function(){
MapIt = function() {
ListIds = '1234';//selected_Listings.join();
if (navigator.appName == "Microsoft Internet Explorer") {
var opts = "screenX=0,screenY=0,width=" + screen.width + ",height=" + screen.height;
} else {
var opts = "outerWidth=" + screen.availWidth + ",outerHeight=" + screen.availHeight + ",screenX=0,screenY=0";
}
var urlStr = "http://wwwd.dev.theabc.com/bingmaps/Map";
$('<form action="'+urlStr+' target="submission" onsubmit="window.open(\'http://www.google.com\',\'Map\',\''+opts+',toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no\');return true;" method="post"><input type="hidden" value="'+ListIds+'"></form>').submit();
}
});
</script>
</head>
<body>
<button id="run" onclick="MapIt()">run</button>
</body>
</html>

JavaScript string doesn't get displayed on the page

pretty new to javascript and doing some examples from a book, can't understand why this isn't producing any text strings on the page when loaded.
function init()
{
var sum = 80 + 20;
var sub = sum - 50;
var mul = sum * 5;
var div = sum / 4;
var mod = sum % 2;
var inc = ++sum;
var dec = --sum;
var str = "Sum: " + sum;
str += "<br>Subtraction: " + sub;
str += "<br>Multiplication: " + mul;
str += "<br>Division: " + div;
str += "<br>Modulus: " + mod;
str += "<br>Increment: " + inc;
str += "<br>Decrement: " + dec;
document.getElementById( "Panel" ).innerHTML = str;
}
document.addEventListener("DOMContentLoaded" , init , false);
And the html5 code;
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="arithmetic.js"></script>
<title>Doing Arithmetic</title>
</head>
<body>
<div id="panel"> </div>
</body>
</html>
Your <div> has an id of panel, not Panel. The IDs need to match. So you can either change the JavaScript code:
document.getElementById( "panel" )
or the HTML:
<div id="Panel"> </div>
Replace
<div id="panel"> </div>
with
<div id="Panel"> </div>
and it will work. P in panel should be capital.

Categories

Resources