How would I go about disabling/enabling a button when the UNIX timestamp reaches <= 0.
I use AJAX to continuously call a .php-file every 250ms. In this .php-file I check if its been 90 seconds since last action was taken by comparing the time (in UNIX) now to the last time I pressed the button (using a MySQL database).
The comparison is done by subtracting time it was pressed to the time now.
I would like to enable the button when the UNIX timestamp when there's less than or equal to 0 seconds since the button was last pressed.
Having a cooperation between PHP and JavaScript is a challenge, I know that, but I also know there are ways to do this.
Thanks in advance.
You could do this with jquery depending on what the script is about. Rather than calling ajax, you could assign an attribute to the time and then using a jquery setInterval function decrease the time by 1 second and then check whether the time is less than 0 or not?
Example:
HTML:
<input type='submit' id='button' name='button' data-time='(using php, put the seconds in here' />
Jquery
$(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);
});
You can just use javascript or jQuery to disable the button by changing it's disabled property. You can use javascript to change it back also.
Example: document.getElementById("myBtn").disabled = true;
Read more here: http://www.w3schools.com/jsref/prop_pushbutton_disabled.asp
Related
I have a bit of code, which refreshes my HTML page, everytime there is a new minute i.e. when seconds == 0.
<head>
<script>
function reload(){
location.reload();
}
function refresh(){
var d = new Date();
var s = d.getSeconds();
if (s == 0) {setTimeout(reload(), 1000)};
}
</script> </head>
<body onload="refresh(), setInterval('refresh()',1000)">
However, when it refreshes, it refreshes an infinite amount of times in the time that seconds == 0. I have tried to implement "setTimeout", in order to prevent this from happening - and so that it only refreshes once. However, this did not work and it is still refreshing an infinite amount of times while s == 0. Does anyone have any more ideas to prevent this from happening? Any questions, just ask. Thanks
If I understand correctly, you don't want to refresh after 1 minute from loading but refresh when second = 0.
You don't have to call refresh function constantly via interval.
We have current second. So, if we subtract from minute, we can find remaining seconds to new minute.
60 - d.getSeconds();
Then convert into milliseconds, set timeout, and page will be refresh exactly at new minute.
setTimeout(function() { location.reload() }, 1000 * (60 - d.getSeconds()));
If so important you can consider add/subtract milliseconds with d.getMilliseconds()
For JavaScript, you can simplify this down to:
setTimeout(() => {
window.location.reload(1);
}, 60 * 1000);
However a very simple solution not using JS is
<meta http-equiv="refresh" content="60; URL=https://example.com/">
In general the refreshin is not a nice way to do things. have you considered using asychronous calls and refreshing your DOM with JavaScript instead of reloading the whole page?
However if you want to pursue this route I'd take the current starting time as a base and check from here is 1 second has passed already.
const t0 = performance.now();
function refresh(){
if ((performance.now() - t0) >= 1000) {
location.reload();
}
}
However you'll need to call refresh untill this happens.
As for the "don't understand" comment, I cleand up a litle and I'll add some explanation here:
The first line is outside of all functions, so it sets a variable "globally", as it never changes I use a cosntant (instead of a variable) for speed and readability. It sets the current time in ms insode t0
const t0 = performance.now();
In your funcion I use the same command to get the ms again, and substract the formerly saved ms from it. If the new number is more than 1000 bigger than the original, a second has passed and it can do the reload.
if ((performance.now() - t0) >= 1000) {...
I'm making a simple game which generates random numbers and user has to enter a value, if users value matches the random value generated, the user wins basically this is a beginner project. I want to make a small counter so that user has a limited time to put in the value and I want that limited time to show on the screen in a label. Lets say that you have to put the value under 30 secs and the timer will count from 1 to 30 every second. The counting from 1 to 30 will update in the label every second. This is the logic I'm trying to work on right now and I can't figure out any other way... If I've done some mistake in code please comment or if you have much more simpler way please post it down below. (pls dont vote down im at threat of account suspension)
Heres the part of my timer code:
if(timer <= 30)
{
for(var i = 0;i >= 30;i++)
{
setInterval(null,1000);
timer++;
document.getElementById("counter").innerHTML = timer+" seconds wasted";
}
alert("Time is over, you lost by "+s);
}
You could create a recursive function.
Say var countDown function(){ time = time--;
setTimeout(countDown, 1000);}
Then you need a variable time that is accessible for the countDown function.
var time = 30;
In the countDown function you could create an updateTimeElement.
Try it out.
The setInterval function has 2 parameters, a callback (an anomynous function in javascript thats triggered) and the milliseconds between each trigger of the interval.
What you are doing in your script is making an interval with nothing to do each second (this runs indefinately), then increment the timer integer and updating the DOM. However, this all executes within seconds.
I'd suggest (before you use a function) you look at the documentation to see how you can improve your script to work as you intent to ;-) Here are a few links that might help you get started:
http://www.w3schools.com/js/js_timing.asp
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
I wont be doing the work for you, since this is a good exercise for a beginner programmer ;-)
If you can't figure it out, leave a comment below this answer and I'll get back to you to help you if you need further assistance.
I am working on a module in which there is a requirement to show a timer which shows only seconds. The timer must start from 30 and keep on decrementing down to 0; and after that fire some action and again start from 30. How can I achieve this in javascript?
There you go :)
var timer = 30;
function decrementAfter1Second(){
setTimeout(function(){
timer--;
if(timer==0){
doWhateverYouWantAfter30Seconds();
timer = 30;
}
decrementAfter1Second();
}, 1000);
}
decrementAfter1Second();
Now next time you want to do something in javascript don't be a slacker and read something about the language first ;) because right now i'm assuming you either don't know how to program or you don't know how to use google.
You could use setTimeout and clearTimeout. Have the timeout fire every 1 second and then invoke clearTimeout when seconds == 0.
You can find examples of both functions here.
I want to restart my count up timer every 5 seconds from the following example: http://jsfiddle.net/stursby/wYUzq/5/
So far, it starts and stops fine, even resets. I would just like to have it automatically go back to 0 and start counting up again after, say, 5 seconds.
I've tried using setInterval() but got weird timing resets from that.
you could add this check in your display() function
if (ms / 5000 > 1)
{
swreset();
startstop();
}
I would use modulos to update the display accordingly. Replace:
$('#count span').text(ms);
with:
$('#count span').text(ms%5000);
at every occurrence.
Let me explain what I'm trying to do.
I want to make a simple box which counts down numbers at intervals I specify.
For example, I'd like to set it to start at 150, and then I want to set it to drop by 15 every 30 seconds.
Is this possible with AJAX/Javascript? If so, could someone point me in the right direction?
Would really appreciate any help on this script, been Googling for hours now! :(
Cheers
Kieran
Have a look at the setTimeout or setInterval methods, they allow you to execute a function after a specified number of milliseconds (1000ms = 1second). Use that, to call a function that keeps dropping the number and writes it to a HTML element to the user can see it.
this isn't tested, but i hope it shows you the way to go.
var start = 150;
var drop = 15;
var interval = 30;
function countdown(){
document.getElementById('mybox').innerHTML = start;
start-=drop;
window.setTimeout("countdown",interval*1000);
}
countdown();
You may use jQuery to do that, see http://keith-wood.name/countdown.html -> tab Callbacks
Keep in mind that 30 seconds in my browser are not necessarily equal to 30 seconds in your browser. It depends on the workload of the browser.
The time difference is minor for a short time but can increase over a long time. The times will drift apart. If the times must not be equal (or nearly equal) between two visitors than such simple solution should be fine.
We had once a problem to introduce a live clock / countdown in one of our projects. We build a script with javascript, ajax and PHP for clock synchronisation (server time was timeserver).
You should use setInterval / clearInterval which is made for this kind of tasks:
function cooldown(element, start, stop, step, delay) {
var current = start;
element.innerHTML = current;
var timer = setInterval(function () {
current -= step;
if(current < stop) current=stop;
element.innerHTML = current;
if(current == stop) clearInterval(timer);
}, delay*1000);
}
Demonstrated here : http://jsfiddle.net/PCMHn/