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/
Related
I'm doing an easy slider with buttons, it works fine, but I'd like to add TimeOut() function to current code, to allow slides to change automatically.
I tried to do that with jQuery but it didn't work.
$('.reviews-slider-button').click(function() {
var i = $(this).index();
$('.reviews-slider-person').hide();
$('.reviews-slider-person-' + (i + 1)).show();
});
I'd like to change automatically slider every 10 seconds, and when I would click on .reviews-slider-button it would reset the timer ( to avoid situation I click to change slide, and timer automatically change to the next one).
I'd be grateful for your advice's.
You can use setInterval to click your button every 10 seconds:
var timer = ''; // Make global variable
function ScrollAuto() {
temp = setInterval(function() {
$('.nextButton').click();
}, 10000)
return timer;
}
And to reset your timer, inside your reset button add:
clearInterval(timer);
Similarly to the answer from Shree, but make it cleaner, but use timeout, not interval, you want the system to change slide every 10 seconds unless you click, in which case you reset the timeout, go to the next slide, and set up the next timeout
Something like this:
var slideMaxDuration = 10000; // in ms
var slideTimer = void 0;
function nextSlide() {
clearInterval(slideTimer);
// ... go to next slide ...
}
function autoContinue() {
nextSlide();
setTimeout(autoContinue, slideMaxDuration);
}
$('.reviews-slider-button').click(autoContinue);
You also need to set up the initial autoContinue when you want the whole thing to start.
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 am currently trying to make a visual countdown for my user for when the animation is finished. My current attempt looks somewhat like this:
function setClassAndFire(){
timer = setInterval(function () {
t--;
$(this).attr('class', 'timerAnimation');
countdownTimer();
if (t === 0) {
clearInterval(timer);
timer = undefined;
funcForCall();
}
}, 1000);
}
function countdownTimer(){
var timerCurrentWidth = $('.timerAnimation').width(),
timerMaxWidth = $("#awardQueueText").width(),
pxPerSecond = timerMaxWidth / 60,
currentCountdown = timerCurrentWidth / pxPerSecond;
currentCountdown = Math.round(currentCountdown);
document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
"<span style='white-space : nowrap;'>" + currentCountdown + " sec.</span>";
}
Important to know is that the animation only displays the time until we may be able to send an API call. So the animation will be re-engaged if we have something in queue.
So as you can see my current attempt works, but is some-what cluncky:
The countdown sometimes fails to subtract a second and "fixes"
that with a 2 seconds subtract in the next attempt.
This is probably caused by the Math.round() for currentCountdown, but is there a work around for that? I mean I have the max possible width of the animation object and can seperate it from the current width.
Is there a way to bring it to work? We need to relate the timer to the animation to achive desired behavior. So when the animation count hits 25, I want that the displayed number is 25 as well!
You got this problem because you got the number from the width andh the width can't have decimals (or better, they can be but they are gonna be truncated sometimes).
So my suggestion is to use a differente variable for the number you will show and the width of the DOM element.
It seems to me that the variable t is what I am talking about, so just try to use it.
function setClassAndFire(){
timer = setInterval(function () {
t--; //What is t?
$(this).attr('class', 'timerAnimation');
countdownTimer(t);
if (t === 0) {
clearInterval(timer);
timer = undefined;
funcForCall();
}
}, 1000);
}
function countdownTimer(t){
document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
"<span style='white-space : nowrap;'>" + t+ " sec.</span>";
}
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.
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