Auto refresh a page with count down time - javascript

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.

Related

I'm having problem on auto refreshing a content in a web page

I'm creating a webpage that will automatically refresh a content to always get the latest data in the database. This is my code in Javascript.
setInterval(function() {
$("#status").load('refresh.php');
},1000);
In my javascript, I'm automatically refreshing the #status with refresh.php every second.
But when I inspect the element of my webpage and click on the network. It is also requesting(spamming) the refresh.php every second which is I think a bad practice.
Can you help me how to fixed this? Or can you suggest better ajax code to auto refresh a content without requesting the php file too much?
You should probably use a websocket for this, get the latest status as data from the server and then change only that section of the page using javascript
This code will be request refresh.php later at timeouts.min every time when new (requested) value of #status is equal to current. If values are different, next timeout will be timeouts.min again.
var timeouts={
min:1000, // min await timeout = 1s
max:16000 // max await timeout = 16s
};
var currentTo = timeouts.min;
function setAutoRefresh( to ){
setTimeout( function() {
var current = $("#status").text();// or .html()
$("#status").load('refresh.php', function() {
// if we are load a new value
if( current !== $("#status").text()) {
currentTo = timeouts.min;
// if loaded value are same to current
} else {
currentTo += timeouts.min; // or currentTo *= 2; for example
if( currentTo > timeouts.max ){
currentTo = timeouts.max;
}
}
console.log('Next #status refresh after ' + currentTo + 'ms');
// Set a new timeout
setAutoRefresh( currentTo );
});
}, to);
}
// Set the first timeout
setAutoRefresh( timeouts.min );

Show the count up timer result on the page

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

disable button with PHP and JavaScript when time is gone

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'>

Function in javascript won't update directly, have to refresh page

In my javascript
$(document).ready(function() {
console.log((new Date().getTime() / 1000));
if ((new Date(setting.lastDate).getTime() / 1000) <= (new Date().getTime() / 1000)) {
$('.Go').removeAttr("disabled");
$( ".headertesting").replaceWith(" ");
$( ".testing" ).replaceWith( "<span class='butlabel testing' >Register Now!</span><span class='spinner'></span>" );
}
});
In my html when i run this function . It's not worked as i expected
I have a countdown date:
Example i set
lastDate = "06/01/2016 10:21:00"
So it will check my currentTime and compare it. But when it reach. the button didn't update directly. I have to refresh the page only see the result. What i want is directly button change without refresh page once time reached.
That's because $(document).ready() executes only once, when the page loads. You're probably expecting that your function executes repeatedly, maybe every second or so, so that it updates as soon as the timer reaches that condition. Try window.setTimeout or window.setInterval. Here's a related question with a good answer: What's the easiest way to call a function every 5 seconds in jQuery?.
When you say "is not working", what did you try?
var resultsEl = document.getElementById("time");
window.setInterval(function(){
resultsEl.innerText = new Date().toLocaleTimeString();
}, 1000);
<div id="time" style="height: 1em; background-color: aliceblue;"></div>

How to show last 5 seconds when timing is running out?

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);
}

Categories

Resources