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
Related
I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>
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.
So I have a function that processes some user input and then displays the results. What I would like to do is have the displayed results toggle between two sets of text. The function runs when I click a button on the page. Currently I have it set to display a different message depending on what time the button is clicked.
myFunction1()
{
// does a whole bunch of other stuff...
myFunction2(value1, value2, today.getSeconds());
}
myFunction2(x, y, z)
{
if (z % 10 >= 5)
document.getElementById("element1").innerHTML= x + " My Text " + y ;
else
document.getElementById("element1").innerHTMLx + " Alt Text " + y ;
}
So instead of this I would want the myFunction2 to repeat every 5 seconds, toggling the text each time. I tried using setTimeout but I didn't seem to have much luck. Maybe I wasn't using it correctly. I want to only have to click the button once and have the text continue switching until I reset the form. Thanks in advance!
You can use setInterval to trigger a function periodically, something like this:
setInterval(
function(){ myFunction2(value1, value2, today.getSeconds()); },
5000
)
You can trigger it when you click your button the first time.
You can use setInterval to toggle every 5 seconds:
var myVar = setInterval(function () {
myTimer();
}, 5000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
DEMO http://jsfiddle.net/skhan/nz6Jf/
As I don't have much knowledge of javascript and I need your help. My problem is like this:
I am using setInterval() for increasing the value of i every after 1 minutes and I am using this code:
var i = minutes;
function decrementMin() {
if(i>=0)
{
i--;
}
if(i==0)
{
alert('Minute = Congratulation your time begin now!');
}
document.getElementById('minutes').innerHTML = i + "minutes";
}
setInterval('decrementMin()',60000);
The problem is I want to show first message in <div id='minutes'></div> when page loads, but it shows the message after 1 minutes interval. If there is something that I am missing in my code please let me know.
Your problem is that you are setting the interval before the first message is displayed. Instead, you can call the function straight away and then set the interval. Also, you need to clear the interval once you've reached 0:
var i = minutes;
var intID;
function decrementMin() {
if(i>=0)
{
i--;
}
if(i==0)
{
clearInterval(intID);
alert('Minute = Congratulations my friend your time begins now!');
}
document.getElementById('minutes').innerHTML = i + "minutes";
}
decrementMin();
intID = setInterval(decrementMin, 60000);
This way you call your function straight away, and then set it to run every minute. Once you reach 0, you clear the interval so that the function doesn't count to "-1", etc.