I'm creating a piano tiles game from javascript using canvas, I have a case where the user has to press a button in an exact location and time. I have to give the user a 100ms tolerance so if the user pressed the button 100ms earlier or later it still counts.
A solution would be appreciated.
The yellow and blue blocks are the tiles so the user has to press the keys at the exact time and location of the tiles
Usually, it is best not to mix representation with the underlying logic.
You need to represent the task (note to be played/button pressed) along with the time (or time offset when do you expect it. Then once the button is pressed compare if the current time matches the expected time.
here is a toy example that may give you ideas
var startTime = 0;
$(document).ready(function(){
$('#butt').on('click', function(){
var curTime = new Date().getTime();
if (startTime === 0)
{
startTime = new Date().getTime()
$('#log').val('Now try pressing it exactly every second')
}
else
{
$('#log').val('You were off by ' + (curTime - startTime - 1000)+'ms');
startTime = curTime
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="butt">
Press me once a second
</button>
<textarea id='log' rows=10 cols=50>Click button to start</textarea>
Related
I have a Javascript function which are doing the following functions,
Hide a div content when a button click.
Getting a input time (h:m:s) from a html input field and countdown them.
Showing the counting result in a html p tag.
function countdownTimeStart() {
/* hide the timer panel div when start button click*/
document.getElementById('timer_panel',).
innerHTML=document.getElementById('time_count').innerHTML;
/* Start count the time in timer panel */
/* Start count the time in timer panel */
var time = document.getElementById("picker-dates").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0], time[1], time[2]);
var x = setInterval(function() {
// set hours, minutes and seconds, decrease seconds
var hours = time[0];
var minutes = time[1];
var seconds = time[2]--;
// if seconds are negative, set them to 59 and reduce minutes
if (time[2] == -1) {
time[1]--;
time[2] = 59
}
// if minutes are negative, set them to 59 and reduce hours
if (time[1] == -1) {
time[0]--;
time[1] = 59
}
// Output the result in an element with id="demo"
// add leading zero for seconds if seconds lower than 10
if (seconds < 10) {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + "0" + seconds + " ";
} else {
document.getElementById("demo").innerHTML = hours + ": " + minutes + ": " + seconds + " ";
}
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "00:00:00";
}
}, 1000);
}
<div id="timer_panel" class="timer_panel1>
<input type = " text " id = "picker-dates ">
<button id="start " onclick="countdownTimeStart(); ">
</div>
<div id="time_count " class="time_count " style="visibility:hidden;>
<p id="demo" class="count"></p>
</div>
Problem is the time counting result not showing inside of the "demo" p tag when hiding timer panel div. How can I solve this, can anyone help me !
I've noticed a few mistakes in your code, I'll try to outline them as clearly as I can for you.
HTML
Firstly in your HTML you haven't closed your input tags. Also there was a typo on your div with the id time_count that didn't have closed quotations.
As some other people have mentioned, you also had a typo in your id name.
But the biggest thing, is that your p tag is wrapped in the div that inline you have set to visibility:hidden. Your JS doesn't address this. Once I moved the p tag out from this div, I was able to see an output.
However...
JavaScript
The Javascript code has some minor adjustments too. Why do you create a date object that you don't use? I'd delete this is you don't need it.
I would also suggest you store your element for use later, rather than calling document.getElementById('demo') everytime you use it, like so:
var el = document.getElementById('demo');
How to stop once the timer reaches 0
I've added this logic to your if else block
if( seconds == 0 && minutes == 0 && hours == 0 ){
clearInterval(x);
el.innerHTML = "00:00:00";
}
It uses code that you were trying to implement earlier but wasn't quite right. Moving it to here should do the trick. Check out the codepen where I have updated the code also.
Cancel the timer
Firstly you'll need to add a new button to your HTML
<button id="cancel">Cancel</button>
Then within your setInterval function I've added the following code:
// select cancel button
var cancel = document.getElementById('cancel');
// set up cancel functionality
// create a function to handle the cancel
function cancelCountdown(){
el.innerHTML = "00:00:00";
clearInterval(x);
}
// attach listener to cancel
// if cancel button is clicked
cancel.addEventListener( 'click', cancelCountdown);
Pause the timer
Okay, so we need to add another button to your HTML with a id of pause like so:
<button id="pause" >pause</button>
Then we add this pause functionality just below the code we put
in to clear the timer.
// select the pause button
var pause = document.getElementById('pause');
// create pause function
function pauseCountdown(){
// grab the current time
let pauseTime = hours+":"+minutes+":"+seconds;
// set that time into the timeInput
// so that next time 'Start' is pressed
// the paused time will be used
let timeInput = document.getElementById('picker-dates');
timeInput.value = pauseTime;
// stop the time to 'pause'
clearInterval(x);
}
// add listener to catch the pause
pause.addEventListener('click' , pauseCountdown);
How does it work? Well we're kinda cheating. You can't pause an Interval timer (that I've been able to find anyway) but you can take
the values you're using for the time and store them. Then when the start button is pressed, the timer will start again with the paused interval time as the countdown time. I hope that makes sense. Check out the codepen to see the example working.
Hope this helps!
Cheers,
Your p element has id demo1, but your code uses demo.
I'm making a webpage where user events are logged in.
To test the feature I made a small, independant webpage with a teaxtarea and a text input. The events logged are those performed on the input element.
I want to prevent the same event text to be shown multiple times in a row, but I can't seem to prevent them from showing up!
I also want to add a line to separate event groups 0.5 seconds after no other event happened, but the line seems to appear on every event trigger, evenif I use clearTimeout with the timeout ID.
Basically: I don't want any line to be repeated. If the last line is a separator line, then it must not add another one. Yet it doesn't see to work.
JSFiddle Demo
Here is my code:
JavaScript
var timerID = 0;
function addSeparateLine()
{
document.getElementById('listeEvenements').value += "--------------------\n";
}
function show(newEventText)
{
var eventListField = document.getElementById('listeEvenements');
var eventList = [];
if (eventListField.value.length > 0)
{
eventList = eventListField.value.split("\n");
}
var eventCounter = eventList.length;
if (eventList[eventCounter - 2] == newEventText)
{
clearTimeout(timerID);
newEventText = "";
}
timerID = setTimeout(addSeparateLine, 500);
if (newEventText !== "")
{
eventListField.value += newEventText + "\n";
}
return true;
}
HTML
<fieldset id="conteneurLogEvenements">
<legend>Events called from HTML attribute</legend>
<textarea id="listeEvenements" rows="25"></textarea>
<input id="controleEcoute" type="text" onBlur="show('Blur');" onchange="show('Change');" onclick="show('Click');" onfocus="show('Focus');" onMousedown="show('MouseDown');" onMousemove="show('MouseMove');" onMouseover="show('MouseOver');" onkeydown="show('KeyDown');"
onkeypress="show('KeyPress');" onkeyup="show('KeyUp');" />
</fieldset>
http://jsfiddle.net/z6kb4/2/
It sounds like what you want is a line that prints after 500 milliseconds of inactivity, but what your code currently says to do is "print a line 500 milliseconds after any action, unless it gets canceled". You can get better results by structuring the code more closely to your intended goal.
Specifically, instead of scheduling a new timeout every time an event occurs, simply start a loop when the first event occurs that checks the time that has elapsed since the most recent event received and then prints a line when the elapsed time exceeds the desired threshold (500 milliseconds). Something like:
function addSeparateLine() {
var elapsed = new Date().getTime() - lastEventTime;
if (elapsed >= 500) {
document.getElementById('listeEvenements').value += "--------------------\n";
clearInterval(timerID);
timerID = -1;
}
}
...and then you schedule it like:
if(newEventText !== "") {
lastEventTime = new Date().getTime();
eventListField.value += newEventText+"\n";
if (timerID == -1) {
timerID = setInterval(addSeparateLine,100);
}
}
Working example here: http://jsfiddle.net/z6kb4/4/
Because you are not actually stopping the show function in any way. The clearTimeout only applies to the separator add. I have updated your fiddle. You need to wrap your function with
if (+new Date() - lastfire < 500) return;
and
lastfire = +new Date();
(before the last return--see the updated fiddle). Also, make sure to stick the global definition var lastfire = -1; somewhere up top.
The below code (I just gave a snippet of working code) animates a few images based on time. Something like a Flash animation where at certain times images start to move at certain times or frame count. My question is , is there a better way to do this ? I know I can use something other than setInterval . I am calculating the elapsed time and setting off images based on the time interval.
It is the ClassLoadImages.prototype.m_draw which is the issue.
function doGameLoop() {
ctx.clearRect(0,0,600,400);
now = new Date();
totalSeconds = (now - start) / 1000;
last = now;
ctx.fillText("totalSeconds=" +totalSeconds ,10,100);
if (totalSeconds>2 && totalSeconds<6)
{
img2.m_draw(130);
}
if (totalSeconds>4 && totalSeconds<8)
{
img3.m_draw2(230);
}
if (totalSeconds>10){
start = new Date();//start again
}
img.m_draw(30);
// fi++;
}
var img= new ClassLoadImages(30,30);
var img2= new ClassLoadImages(30,30);
var img3= new ClassLoadImages(30,30);
</script>
If you want something like flash movieclips, check out SpriteClip on github. https://github.com/wolthers/SpriteClip.js
I'm using the following script and the later onclick-event. If I use the onclick my rotating banner loses it and starts displaying pictures at random intervals. I think I should override the "setTimeout" at the end of the first piece of code. Question is how exactly?
<script language="JavaScript" type="text/javascript">
<!--
var RotatingImage1_Index = -1;
var RotatingImage1_Images = new Array();
RotatingImage1_Images[0] = ["images/ban_image1.png","",""];
<!-- 15 Images in total-->
RotatingImage1_Images[14] = ["images/ban_image2.png","",""];
function RotatingImage1ShowNext(){
RotatingImage1_Index = RotatingImage1_Index + 1;
if (RotatingImage1_Index > 14)
RotatingImage1_Index = 0;
eval("document.RotatingImage1.src = RotatingImage1_Images[" + RotatingImage1_Index + "][0]");
setTimeout("RotatingImage1ShowNext();", 4000);}
// -->
</script>
<img src="images/ban_image1.png" id="ban_img1" name="RotatingImage1">
This part works as it should.
<div id="ban_next" align="left">
<a href="#" onclick="RotatingImage1ShowNext();return false;">
<img src="images/ban_next.png" id="ban_nxt1"></a></div>
This part works as well, but only correctly if I set the 'setTimeout' to '0'. I am sorry, I'm compleatly new to this. I was looking at this stackoverflow.com question, but I don't know how to implement that here.
I thank you in advance.
Edit:
The rotating image starts automaticly. It displays a new image every 4 seconds. The images have text on them, or better insider jokes. Readers should be tempted to read them, but if the automated rotation cought there antention, the have to keep that antention for a full minute to see all images. That's probably to long. So I thought to implement a button to overwrite the timer and show the next image 'on click'. But after the click the rotation-time should turn back to auto-rotation. That's the plan.
Thank you Prusse, for now it bedtime, I will try to grasp your answer tomorrow ;)
You don't need eval, just do document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0].
The described behavior happens because there is more then one timer firing. There is one set on the first time RotatingImage1ShowNext is called, more one each time its called from your onclick handler. To fix this declare a global for your timer and before another timeout is set clear it if set. Like:
var global_timerid;
function RotatingImage1ShowNext(){
//RotatingImage1_Index = RotatingImage1_Index + 1;
//if (RotatingImage1_Index > 14) RotatingImage1_Index = 0;
RotatingImage1_Index = (RotatingImage1_Index + 1) % RotatingImage1_Images.length;
//document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0];
document.getElementById('ban_img1').src = RotatingImage1_Images[RotatingImage1_Index][0];
if (global_timerid) clearTimeout(global_timerid);
global_timerid = setTimeout(RotatingImage1ShowNext, 4000);
}
I want to calculate the time between two clicks of an attribute with javascript but I don't know how.
For example;
click here
if the user clicks more than once -let's say in 5 seconds- I want to display an alert. I'm using jQuery if that helps. I don't know much about javascript but I've been coding a small project in my free time.
Something like this would do the trick. Keep a variable with the time of the last click and then compare it when the user clicks the link again. If the difference is < 5 seconds show the alert
<a id='testLink' href="#">click here</a>
<script type='text/javascript'>
var lastClick = 0;
$("#testLink").click(function() {
var d = new Date();
var t = d.getTime();
if(t - lastClick < 5000) {
alert("LESS THAN 5 SECONDS!!!");
}
lastClick = t;
});
</script>
The following may help you getting started:
var lastClicked = 0;
function onClickCheck() {
var timeNow = (new Date()).getTime();
if (timeNow > (lastClicked + 5000)) {
// Execute the link action
}
else {
alert('Please wait at least 5 seconds between clicks!');
}
lastClicked = timeNow;
}
HTML:
click here
Create a variable to hold the time of a click, say lastClick.
Set up a click handler for the element you want to track clicks on.
Inside the handler, check for a value in lastClick. If there is no value, set it to the current time. If there is a value, compare it against the current time. If the difference is within the range you're checking for, display the alert.
Start with
var lastClicked = (new Date()).getTime(); //not zero