I am trying to code for a test get people's tap frequency with music.
Here is something without the music, but people can tap on their laptop touch pad to get the data. However, the data seems not accurate enough, for example it at least be 200 milliseconds. and when we steady tap it, it offered a quite variable result. someone can tell me how to improve it?
Here is my code:
<!DOCTYPE html>
<html onclick="myFunction()">
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>Click</title>
</head>
<body>
<script>
function myFunction() {
inner = document.getElementById("time").innerHTML;
if(inner === ""){
document.getElementById("time").innerHTML = Date();
}
else{
var curr = new Date();
console.log(curr);
var past = new Date(inner);
console.log(inner);
console.log(past);
var gap = curr.getTime() - past.getTime();
console.log(gap);
document.getElementById("time").innerHTML = curr;
var gapText = document.getElementById("gap").innerHTML;
gapText = gapText + gap + "<br>";
document.getElementById("gap").innerHTML = gapText;
}
}
</script>
<div><text>The current time is </text><text id="time"></text></div>
<div><text>The tap durations are (milliseconds):</text></div>
<div><text id="gap"></text></div>
</body>
</html>
I also got a large variable of time differences with your code on a MacBook Pro running in Chrome. Then I refactored your code and got significantly better performance, generally within ~30ms. Matthew Herbst is right, hardware is going to play a factor, but I think there are ways to improve performance. My refactored code is below, but a couple of observations:
Take out all the console.logs. They don't affect performance too much, but when you're worried about a handful of milliseconds, they do.
Only interact with the DOM when you absolutely have to. For instance, you're going to the DOM to get the last timestamp, in order to calculate the current value. Save it in a variable, it's faster.
Here's my code, let me know how well it works for you. Hope this helps.
<!DOCTYPE html>
<html onclick="myFunction()">
<head>
<link rel="stylesheet" type="text/css" href="main.css">
<title>Click</title>
</head>
<body>
<script>
var newTime;
function myFunction() {
if (newTime === undefined){
newTime = new Date();
// This will only run once
document.getElementById("time").innerHTML = newTime;
}
else{
// Here I'm not getting values from the DOM. I'm saving the value as a variable.
var oldTime = newTime;
newTime = new Date();
var gap = newTime.getTime() - oldTime.getTime();
var gapText = gap + "<br>";
document.getElementById("gap").innerHTML = gapText;
}
}
</script>
<div><text>The current time is </text><text id="time"></text></div>
<div><text>The tap durations are (milliseconds):</text></div>
<div><text id="gap"></text></div>
</body>
</html>
Related
I have a function that continues one step longer than needed. When the image (elefant.png) is clicked the image (scale1.png) is changed. There are 5 pictures and it works fine. Problem is that when the last picture is displayed, and I click (elefant.png) again it comes to an undefined picture? I don't understand why it doesn't just stop on the last picture (scale5.png)?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<link rel="stylesheet" href="style.css">
<body>
<div class="wrapper1">
<h2 id="title_text">Hey</h2>
<img src="image/scale1.png" id="getImage">
<img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">
</div>
<script type="text/javascript">
var counter = 0,
gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
imagefun = function () {
document.getElementById("getImage").src = gallery[counter];
counter++;
if (counter >= 4) {
document.getElementById("title_text").innerHTML = "New text!";
}
};
</script>
</body>
</html>
This might be an easy fix, but I am not good with javascript. I tried searching for an answer but I'm not sure what to even look for as I don't know what causes the issue?
I'm not exactly sure what your end result should be once you hit the end of your gallery array but as it stands it changes title_text to "New text!".
The problem with your code as it stands is you always increment counter and change the source getImage based on that integer. That doesn't stop once your counter hits 4.
I'd use the array length as a stopping point and only increment the counter variable up until that limit is hit. I would write something like this:
var counter = 0,
gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
imagefun = function () {
if (counter >= gallery.length) {
document.getElementById("title_text").innerHTML = "New text!";
}
else{
document.getElementById("getImage").src = gallery[counter];
counter++;
}
};
<div class="wrapper1">
<h2 id="title_text">Hey</h2>
<img src="image/scale1.png" id="getImage">
<img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">
</div>
You always run the function and change the image source, and only then check for counter's value. That's why it'll keep going and changing the source even when counter is bigger than 3.
A solution would be to change counter' s value conditionally:
if (counter < gallery.length - 1) {
counter++;
}
I've written some code in html and javascript and when I drag it into chrome to test it, I get error code 5 in return. I've tried everything that chrome itself recommends when this happens as well as trying with different code, which works. heres my code:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var x = 1
var total = 0
var increment = 1
setInterval(function(){ total + increment; }, 1000);
while (x = 1) {
$(document).ready(function(){
$("#id").click(function(){
$("h1").text(total + 1);
});
});
}
</script>
</head>
<body>
<h1>0</h1>
<button id="id">??????????</button>
</body>
keep in mind, I'm extremely new to both of these languages, so I'm learning as I go.
There are some issues in your code:
your while loop runs forever since x=1 will remain true (which is causing the error), furthermore x isn't changed in the loop
the function in setInterval is doing nothing since there is no assignment =
Anyway, you don't need the most stuff. It is enough to get the value of h1 and increment it directly. If the script tag is put before the closing body tag you don't need the $(document).ready-part. So the following is all javascript you need:
Working example:
$("#id").click(function() {
$("h1").text(parseInt($("h1").text()) + 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>0</h1>
<button id="id">??????????</button>
By the way, you don't need jQuery for that and can use plain javascript.
Working example:
document.getElementById('id').addEventListener('click', function() {
document.querySelector("h1").textContent = parseInt(document.querySelector("h1").textContent) + 1;
});
<h1>0</h1>
<button id="id">??????????</button>
You don't have to declare variable x at all. Also, you don't need while loop.
Your loop will go to infinity because condition while(x=1) will be always true.
I guess infinite while loop crashes your Chrome browser.
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var total = 0
$(document).ready(function() {
$("#id").click(function() {
total++;
$("h1").text(total);
});
});
</script>
</head>
<body>
<h1>0</h1>
<button id="id">??????????</button>
</body>
This is my first time working with prompt(). I have completed the assignment to the specifications given by the teacher, however I am really annoyed that the prompt() gets called before the content in the background gets called (I even used window.onload = function() {blah}; but it still gets called before the content is displayed.
The link to the page is http://homepage.cs.uiowa.edu/~csoultz/ and click on lab4
This is not a huge concern more so a curiosity of mine. I have been researching it for the last few hours and have found nothing. I don't want to load anymore libraries and if it is not possible without a library please let me know. Thank you in advance for any help
here is the code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Work Week Calculator</title>
<link rel="stylesheet" href="mySite.css">
<script>
function askquestion(question,answer){
var userAnswer = prompt(question.toString());
if(userAnswer!=null) return userAnswer.toLowerCase()===answer.toLowerCase();
};
</script>
</head>
<body>
<h1>A Simple Quiz</h1>
<p><output id="result"></output></p>
<script>
window.onload = function() {
var trivia=[["Which is the most widely spoken language in the world?","Mandarin"],
["The art of paper folding is known as what?","Origami"],
["Bubble tea originated in which country?","Taiwan"]
];
var correct=0;
var total=trivia.length;
for(i=0;i<trivia.length;i++){
if(askquestion(trivia[i][0],trivia[i][1])){
alert("Correct!");
correct++;
}
else{
alert("Sorry. The correct answer is "+trivia[i][1].toString());
}
}
var resultElement = document.getElementById("result");
resultElement.innerHTML = "You got "+correct.toString()+" out of "+total.toString()+" questions correct";
};
</script>
</body>
</html>
I was able to wrap my function in a setTimeout with a timeout value of 10 and the issue was fixed in chrome.
window.onload = setTimeout(function() {
//Do Stuff Here
},10);
I've got an existing single page web application of which I can't change the code. Some users complain that the application is not performing very well.
I would like to monitor the loading time in this way:
Record the time stamp of a click on the page
Record the time stamp of when the rendering of the page has been completed, after ajax requests and some other javascript magic has been done
Calculate the difference between the two time stamps and post it back to the server.
I can easily do step 1 and 3 with jQuery, however I'm not sure what's the best way to approach step 2?
As this seems to be a quite obvious scenario, is there a standard tool set to perform this kind of monitoring?
This helps:
function onLoad() {
var now = new Date().getTime();
var page_load_time = now - performance.timing.navigationStart;
console.log("User-perceived page loading time: " + page_load_time);
}
You could use the global ajaxStop event jQuery offers.
var start = +(new Date());
$(document).ajaxStop(function() {
var diff = +(new Date()) - start;
// do logging
});
This won't include the code executed after the last AJAX call, but if things happening before the last call contain the expected bottleneck, then this will be quite useful.
this can be achieved in following way...
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
var startTime, endTime, timeDifference;
function doIt() {
var startTime = new Date().getTime();
$.ajax({
type: 'post',
url: 'a.php',
success: function (resp) {
endTime = new Date().getTime();
timeDifference = endTime - startTime; //Time Difference is stored in milliseconds
}
})
}
</script>
</head>
<body>
<button style="position: absolute; top:60px" onclick="doIt()">start</button>
</body>
</html>
It's not a perfect solution, however the following code is working. It start the timer when a user clicks. The checkHTML function monitors the changes in the page content.
var timeLogging = new Array();
var timeStart;
$(document).click(function() {
initLogEvent();
});
function initLogEvent() {
caption = $(".v-captiontext:first").text();
timeStart = +(new Date());
timeLogging.push(new Array(0,0));
timeLogging[timeLogging.length - 1][0] = timeStart;
}
initLogEvent();
// Start a timer to check the changes in html
window.setInterval(checkHtml, 250);
// Start a timer to create the reports
window.setInterval(sendReport, 1000);
var html;
function checkHtml() {
current = $("body").html();
if (current != html) {
html = current;
var diff = +(new Date()) - timeStart;
timeLogging[timeLogging.length - 1][1] = diff;
}
}
function sendReport() {
if (timeLogging.length > 3) {
console.log(timeLogging);
// Do additional stuff with the collected data
for (i = 0; i <= timeLogging.length; i++) {
timeLogging.shift();
}
}
}
Are you keeping all you application's markup in the page, even when it is hidden? If so you are probably choking the browser's memory. I recommend learning to offload your markup in localStorage like Bing and Google pioneers a few years ago. I wrote a blog about it the day I discovered the technique and I have used it ever since.
http://love2dev.com/#!article/Use-Local-Storage-to-Make-Your-Single-Page-Web-Application-Rock
I am new to JS and I have a pretty simple-seeming problem.
I want to have a small image that when clicked changes to a different image and at the same time begins playing a looped sound file. When the image is clicked a second time it changes back to the original image and also stops the sound file.
You can think of it as a button that says "start". when "start" is clicked it loops the sound and changes to "stop" and when "stop" is clicked it goes back to start and the sound ceases playing.
I've gotten as far as creating none-displayed checkbox inside of a label which is a square that when checked plays sound and when unchecked stops sound. Problem is I can't get the checkbox to change into different images with "check", "uncheck".
I've also got some code that has a link change images, but I cannot figure out how to make it play the sound.
SO basically i need to combine these two things. BUT I CAN'T figure out how. And I've been googling for the past two days nonstop but cannot find a clearcut and simple answer.
It may help to know that I plan on having many of these small clickable images on the same page, so the Javascript needs to be able to be light but effect all of the links or divs or whatever they are in the end.
Sorry for such a long question. Anybody?
Thanks in advance!
<html>
<head>
<script type="text/javascript">
var pos = 0
var sId = 'sound';
function change() {
if(pos == 0) {
pos = 1;
document.getElementById('btn').src="http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png";
var e = document.createElement('embed');
e.setAttribute('src','beep.mp3');
e.setAttribute('id',sId);
e.setAttribute('hidden','true');
e.setAttribute('autostart','true');
e.setAttribute('loop','true');
document.body.appendChild(e);
} else {
pos = 0;
document.getElementById('btn').src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png";
document.body.removeChild(document.getElementById(sId));
}
}
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="change()" id="btn" />
</body>
</html>
How about that, I think it should work.
Edit:
Here is an OO version that should do what you need:
<html>
<head>
<script type="text/javascript">
function imageSwitch(_imgID,_imgStart,_imgStop,_soundFile) {
this.imgID = _imgID;
this.imgStart = _imgStart;
this.imgStop = _imgStop;
this.soundFile = _soundFile;
this.pos = 0;
this.e;
this.change = function() {
if(this.pos == 0) {
this.pos = 1;
document.getElementById(this.imgID).src = this.imgStop;
this.e = document.createElement('embed');
this.e.setAttribute('src',this.soundFile);
this.e.setAttribute('id','sound'+this.imgID);
this.e.setAttribute('hidden','true');
this.e.setAttribute('autostart','true');
this.e.setAttribute('loop','true');
document.body.appendChild(this.e);
} else {
this.pos = 0;
document.getElementById(this.imgID).src = this.imgStart;
this.e.parentNode.removeChild(this.e);
}
}
}
</script>
<script type="text/javascript">
var abc = new imageSwitch('btn1','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
var def = new imageSwitch('btn2','http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png','http://www.buzzingup.com/wp-content/uploads/2011/07/stop.png','beep.mp3');
</script>
</head>
<body>
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="abc.change()" id="btn1" />
<img src="http://geekoffices.com/wp-content/uploads/2011/07/start-button-300x299.png" onClick="def.change()" id="btn2" />
</body>
</html>