i want to take out the result of the count up timer and show it on the page by clicking on button.
Here's my solution for your problem,
I just made a simple counter and then each time I trigger the click event it will show the current timer value
The code:
//initialisation
var counterLabel = document.getElementById("counter");
var valueLabel = document.getElementById("value");
var totalSeconds = 0;
counterLabel.innerHTML = totalSeconds;
//the loop each 1s
setInterval(setTime, 1000);
//the function that will increase the conter value and save it into the cookie
function setTime() {
++totalSeconds;
counterLabel.innerHTML = totalSeconds;
}
//to get the current conter value
function getTime() {
valueLabel.innerHTML = totalSeconds;
}
<label id="counter"></label>
<button onclick="getTime()">save</button>
<label id="value"></label>
Fiddle:
https://jsfiddle.net/871t3w2o/3/
You can also have a look into localstorage and sessionstorage they both work like the cookie but each one has it own advantages and disadvantages and you should choose the one that satisfy your need
Related
I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled "est" it will display the time in eastern time, when you click "cst" the cst time will display and so on.
Anyways the problem I'm running into is this... I use setInterval(updateTime, 1000); to show the seconds tick up every second, now by doing this when a user clicks on "est" and then another time zone in the dropdown list like "cst" both of those times will appear and disappear every second on top of each other. I want it so when you click on an li element the previous one that was on screen will have the property of display=none. So when u click est for example est time will display and then when u click on cst the est will be display=none and the cst time will display. Man that was a mouthful.
Is there a way to accomplish this and still use the setInterval of 1second?
Here is my code...
<div>
<li>
<ul>
<li id="tmz1">est</li>
<li id="tmz2">central</li>
<li>pacific</li>
</ul>
</li>
<div id="output1"></div>
<div id="output2"></div>
</div>
$(document).ready(function(){
var output1 = document.getElementById('output1');
var output2 = document.getElementById('output2');
document.getElementById('tmz1').onclick = function updateTime(){
output2.style.display = "none";
output1.style.display = "block";
var now = moment();
var humanReadable = now.tz("America/Los_Angeles").format('hh:mm:ssA');
output1.textContent = humanReadable;
setInterval(updateTime, 1000);
}
updateTime();
});
$(document).ready(function(){
var output2 = document.getElementById('output2');
var output1 = document.getElementById('output1');
document.getElementById('tmz2').onclick = function updateTimeX(){
output1.style.display = "none";
output2.style.display = "block";
var now = moment();
var humanReadable =
now.tz("America/New_York").format('hh:mm:ssA');
output2.textContent = humanReadable;
setInterval(updateTimeX, 1000);
}
updateTimeX();
});
Perhaps this will help. I believe you've overcomplicated this just a bit. I've provided comments in the code for you to review.
Note: I did not use moment.js as it is unecessary for your task.
You need:
a time from a Date object
a timezone reference that will
change upon click
an interval that will publish the time (with
the changing TZ)
Someplace to put the output
// place to put the output
const output = document.getElementById('output');
// starting timezone
var tz = 'America/New_York';
// Capture click event on the UL (not the li)
document.getElementsByTagName('UL')[0].addEventListener('click', changeTZ);
function changeTZ(e) {
// e.target is the LI that was clicked upon
tz = e.target.innerText;
// toggle highlighted selection
this.querySelectorAll('li').forEach(el=>el.classList.remove('selected'));
e.target.classList.add('selected');
}
// set the output to the time based upon the changing TZ
// Since this is an entire datetime, remove the date with split()[1] and trim it
setInterval(() => {
output.textContent = new Date(Date.now()).toLocaleString('en-US', {timeZone: `${tz}`}).split(',')[1].trim();
}, 1000);
.selected {
background-color: lightblue;
}
<div>
<ul>
<li class="selected">America/New_York</li>
<li>America/Chicago</li>
<li>America/Los_Angeles</li>
</ul>
<div id="output"></div>
</div>
Assign your setInterval to a variable and clear it when a user selects the new value form dropdown and restart the interval with new value
var interval = setInterval(updateTime, 1000);
if(oldValue !== newValue){
clearInterval(interval)
}
I try to disable Apply button when application deadline is over. I used php and I successfully got time on each button. Now different time is print on different button.
<td><input type='submit' value='Apply' id='button' name='button' date-time='$closedate' /></td>
I used jquery/ javascript to disable button after expired time (after deadline of application), it cannot disable and it always enable.
In the code below code I used for disable button but it not works.
<script>
$(document).ready(function() {
var timer = setInterval(function() {
var current = $("#button").data('time');
// get the current value of the time in seconds
var newtime = current - 1;
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
});
</script>
based on what you have put down, it seems there are a few simple errors that need to be looked at
1) looks like a simple typo -- date-time should be data-time
2) you are not actually outputting the value of $closedate try changing it to
without knowing what the value of $closedate is, we won't be able to help further than that
Here is a fiddle that replicates an example...https://jsfiddle.net/o2gxgz9r/6656/
Your main issue is that you are mispelling the data-time attribute in your code as date-time. Your html should be as follows...
<input type='submit' value='Apply' id='button' name='button' data-time='$closedate' />
After fixing that, you should be able to reference the data value. Moreover, you are not updating the data value, so every time setInterval is called, the variable $closedate remains the same, and so the if statement if (newtime <= 0) is never reached...
var timer = setInterval(function() {
// get the current value of the time in seconds
var current = $("#button").data('time');
// decrement the time
var newtime = current - 1;
// update $closedate
$("#button").data('time', newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
I am not sure what the value of $closedate is but I made an assumption in my fiddle.
A few of issues...
First, in your HTML, you have date-time instead of data-time, so when you go to get the attribute later with: $("#button").data('time'), you won't get anything.
Second, you must remember to convert HTML data (which is always a string) to numbers to do math with them.
Third, you need to verify that $closedate is a string that can be converted into a valid number. You indicated in a comment below that $closedate will be something like: 2017-03-17. But that is not a value that you can subtract from.
Lastly, updating the HTML is costly in terms of performance. You are modifying the data-time attribute upon each iteration of your setInterval(), which is roughly every second. This can and should be avoided. It can be done by keeping the time left in a variable instead of writing it back to the document.
Here's a working version:
$(document).ready(function() {
// Always cache references to elements you will use more than once:
var $btn = $("#button");
// When gettting data from HTML, you get strings. You must convert
// them to numbers to do math with them. Also, we are using 5 seconds
// here instead of $closedate for testing purposes.
var current = parseInt($btn.data('time'), 10);
// Initialize the newtime for comparison
var newtime = current;
var timer = setInterval(function() {
newtime--; // Decrease the time left
// Just testing the variables:
console.log(current, newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$btn.prop('disabled', true);
clearInterval(timer);
}
current--; // Decrease the counter
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='submit' value='Apply' id='button' name='button' data-time='5'>
I found this JS-Countdown Script at JSFiddle.
EDIT:
I'm using the code of rafaelcastrocouto now, which is nearly perfect. I wanted a 10-seconds JQuery Countdown-Script with an interval that resets the countdown timer at 5 seconds and starts over again and again, but only for a specific class with a specific id on the whole HTML page. If it drops to 0, the countdown should stop. Also I want to reset specific counters to 10.
It's about a WebSocket that refreshes every second and depending on the data I get for specific counters I want to reset them or they should count down to zero.
New JSFiddle: http://jsfiddle.net/alexiovay/azkdry0w/4/
This is how I solved with jquery and native setInterval...
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = count.data('seconds');
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
You have sever errors in code, e.g.
setTimeout(cd_go(id), 1000); - should point to function reference not to function execution. setTimeout also returns the timeout id. You must past that id to clearTimeout
clearTimeout(this); it should take id instead of global object (window) or undefined if you are working in strict mode
loop = setInterval(function(id) { … } - id points to undefinded as you are not passing any value for it
I have a small C# code behind to refresh a webform page (form.aspx) after 15 seconds as below:
lblMessage.Text = "<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after 15 seconds)";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setInterval(function(){location.href='/form.aspx';},15000);", true);
Right now the page will be refreshed after 15 seconds. How do I also make the timer count down every second? i.e., 15 => 14 => 13 => ... 1 then refresh so it will be better for users, they will know what is going on with the page...
In javascript I would go with something like this.
<div id='countdown'></div.
var countDown = 15;
function countdown() {
setInterval(function () {
if (countDown == 0) {
return;
}
countDown--;
document.getElementById('countdown').innerHTML = countDown;
return countDown;
}, 1000);
}
countdown();
Fiddle: http://jsfiddle.net/chzzcosy/
"<b><h2>Thank you!</h2></b></br>We will be right with you.<br><br><br>(This page will be refreshed automatically after <span id='counter'>15</span> seconds)"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Success!", "setTimeout(function(){location.href='/form.aspx';},15000); counter = 15; setInterval(function(){counter--; document.getElementById('counter').innerHTML = counter;},1000);", true);
Should do it.
If added a span with id counter around the refresh message number.
Then I added counter = 15; to initialize a default value of 15. And another setInterval to the script block firing every second. With each pass it subtracts one from counter and updates the span with the new counter value. Users should now see the page counting down. I also changed the first setInterval to setTimout, since it's technically a timeout and not an interval that should occur every 15 seconds.
Hi i am using Javascript set timeout to run a certain function.
How do i display the last 10 seconds of the timeout when it is nearing the end?
var a = setTimeout('someFunction()', 10000);
Is it able to display something using the value that it store into the variable?
Thanks
I have created a small demo for you,
http://jsfiddle.net/praveen_prasad/DYaan/1/
<div id="target" style="display:none">
target
</div>
var target,
allotedTimeForWork=100 /*you can change this*/
;
var handler = setTimeout(function(){
if(!target)
{
target=document.getElementById('target');
}
target.style.display="block";
startTicker();
}, allotedTimeForWork);
function startTicker()
{
var counter=10;
var tickerHandler= window.setInterval(function(){
if(counter>0)
{
//cache target
target.innerHTML="you have "+counter +" seconds left";
counter--;
}
else
{
target.innerHTML="time over";
clearInterval(tickerHandler);
}
},1000);
}
It is not possible to directly get the remaining time of a Timeout.
You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.
I would use two timeouts.
The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.
Take a look here: http://jsfiddle.net/VCAnm/
HTML:
<span id="aaa">10</span>
JavaScript:
setInterval(function() {
var elem = document.getElementById('aaa');
elem.innerHTML = elem.innerHTML - 1;
}, 1000);
set 2 timers one for the timeout and another for the warning
var warn_time = 5000;
var function_name = 'someFunction()';
var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);
function warnFunction(function_name, time) {
alert('only ' + time + ' seconds left'); //use a div or whatever to display
var b = setTimeout(function_name, time);
}