I have built a page that store a message and a user to send the message to in a db. The form has a restriction: you can't use the same user for the next 30 seconds from when you have posted the message to the db.
function undisable (id,time){
setTimeout(function() {
$('#'+id).prop('disabled', false);
}, (30000-time));
}
$('#destinatario option').each(function(){
var ds = $(this).attr('data-ts');
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
if(diff < 30000){
$(this).prop('disabled', true);
var id = $(this).attr('id');
undisable(id,diff);
}
});
Now I'd like to add a new condition: you cannot post to any user from the last minute of an hour to the first minute of the next one. So for example you cannot post from 10:59:00 to 11:01:00 (and so on for each hour of the day).
What is the cleverest way to set the if clause to do this?
What I am trying to build is something like:
if(now(minutes) is between 59 and 01){ //this is the point where I get stuck at
$('#sendbutton').prop('disabled', true); //I cannot post
}else{
$('#sendbutton').prop('disabled', false); //I can post
}
Thanks for any help!
You're right, that complicates things. Here's the code to solve your problem. Relies on setTimeouts to disable and enable the button, and you can edit the times you want to disable the button easily.
function time_disabler()
{
var time_disable = 59; // time in minutes to disable the button
var time_enable = 1; // time in minutes to enable to button
var current_mins = new Date().getMinutes(); // current time (minutes)
var current_secs = new Date().getSeconds(); // current time (seconds)
var total_seconds = current_mins * 60 + current_secs; // current time overall in seconds
var last_min_secs = time_disable*60; // time in seconds to disable the button
var first_min_secs = time_enable * 60; // time in seconds to enable the button
// if in between the two times, disable button
if((total_seconds >= last_min_secs && total_seconds < first_min_secs) || (total_seconds < first_min_secs && first_min_secs < last_min_secs))
{
$('#sendbutton').prop('disabled', true); //I cannot post
var time = (total_seconds >= first_min_secs)? first_min_secs + (60*60) - total_seconds : first_min_secs - total_seconds ;
// set time out to recall this function, which will enable it
var t = setTimeout(function (){
time_disabler();
}, time * 1000 );
} else { // if not between the times, disable it
$('#sendbutton').prop('disabled', false); //I can post
// set time out to recall this function, which will disable it
var t = setTimeout(function(){time_disabler();}, ((last_min_secs> total_seconds ? last_min_secs : last_min_secs + 60*60) - total_seconds) * 1000 );
}
}
time_disabler();
-- Old Answer --
You would just use JavaScript's getMinutes() and getSeconds():
var current_mins = new Date().getMinutes();
var current_secs = new Date().getSeconds();
current_mins += current_secs/60;
if(current_mins >= 59 || current_mins <= 1)
{
$('#sendbutton').prop('disabled', true); //I cannot post
} else {
$('#sendbutton').prop('disabled', false); //I can post
}
Related
if(localStorage.getItem("total_seconds")){
var total_seconds = localStorage.getItem("total_seconds");
}
else {
var total_seconds = 10*10;
}
var minutes = parseInt(total_seconds/60);
var seconds = parseInt(total_seconds%60);
function countDownTimer(){
if(seconds < 10){
seconds= "0"+ seconds ;
}
if(minutes < 10){
minutes= "0"+ minutes ;
}
document.getElementById("timer").innerHTML = "Result after: "+minutes+" minutes "+seconds+" seconds";
if(total_seconds <= 0){
setTimeout("document.quiz.submit()" ,1);
document.getElementById("timer").innerHTML = "";
localStorage.removeItem("total_seconds");
} else {
total_seconds = total_seconds -1 ;
minutes = parseInt(total_seconds/60);
seconds = parseInt(total_seconds%60);
localStorage.setItem("total_seconds",total_seconds)
setTimeout("countDownTimer()" ,1000);
}
}setTimeout("countDownTimer()" ,1000);
Above is the code i am using for coutdown using local storage but it doesn't count downs and resume where the user has left if site/browser is closed any tips on how to make it so the coutdown could even work if the user isn't at site or have closed his browser.
Your code only runs while the client browser is open. If your script should look & behave in the way your current code does you will need a server. However, we can make use of the built-in Date object in JavaScript in order to detect how long has passed since the creation of the timer:
const DEFAULT_TIMER_DURATION = 10; // In seconds.
// Here, we get the status of the currently-active timer:
let totalSeconds = parseInt(localStorage.getItem("total_seconds"));
let startDate = parseInt(localStorage.getItem("start_date"));
if(!(totalSeconds && startDate)) {
// If there isn't an active timer, set one up:
localStorage.setItem("total_seconds", DEFAULT_TIMER_DURATION);
localStorage.setItem("start_date", new Date().getTime());
totalSeconds = DEFAULT_TIMER_DURATION;
startDate = new Date().getTime();
console.log("Reset timer:", DEFAULT_TIMER_DURATION);
}
// This function updates the timer and displays the countdown:
function displayElapsedSecond(timerData) {
if(timerData.secondsLeft <= 0) {
console.log("Time is up!");
localStorage.removeItem("total_seconds");
localStorage.removeItem("start_date");
return;
}
if(timerData.initialDelay) {
setTimeout(() => {
displayElapsedSecond({secondsLeft: timerData.secondsLeft});
}, initialDelay);
return;
}
timerData.secondsLeft--;
console.log("Seconds left:", timerData.secondsLeft);
setTimeout(() => {
displayElapsedSecond({secondsLeft: timerData.secondsLeft});
}, 1000);
}
// this block of code calculates how long has passed and continues counting down from wherever the user left of:
const now = new Date().getTime();
const secondsPassed = (now - startDate) / 1000;
let secondsLeft = totalSeconds - secondsPassed;
const initialDelay = Math.ceil(secondsLeft) - secondsLeft;
secondsLeft = Math.ceil(secondsLeft);
displayElapsedSecond({initialDelay, secondsLeft});
// Obviously some improvements can be made for time complexity, but the code nicely illustrates the way this timer works
I'm currently trying to learn JavaScript and I've decided to make things more interesting by actually creating something instead of endless reading & no practice. I'm currently trying to build an alarm clock.
Here's my code:
http://codepen.io/anon/pen/dCsax
function wakeup() {
window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}
I need to create another function that uses setInterval to check every few seconds if the time set in that form is equal to the current time, and if it is, execute the wakeup function that plays Rick Astley - Never Gonna Give You Up.
I don't know how to write this piece of code. Could someone please help me out so I can see how it's done?
Thanks in advance.
For a pure JS solution (no libraries) you should read about Date object
I've forked your example on codepen like this:
function set_alarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
if ( t == 'PM' ) h+= 12;
var now = new Date();
var d = new Date();
d.setHours(h);
d.setMinutes(m);
d.setSeconds(0);
var delta = d.getTime() - now.getTime();
if (delta < 0) delta = -delta;
setTimeout(wakeup,delta);
}
This should give you a hint about what to do.
You can also try using one of the many libraries about dates, expecially moment.js
I added an id to your button, and on click set up the timer function as below:
<input id="scheduleTimer" type="button" value="Schedule alarm"></input>
function getTimeoutSec() {
var dt = new Date();
var currSecs = dt.getSeconds() + (60 * dt.getMinutes()) + (60 * 60 * dt.getHours());
var am_pm = document.getElementById('t').value;
var formHour = parseInt(document.getElementById('h').value);
if(am_pm == 'PM') {
formHour += 12;
}
var formMin = parseInt(document.getElementById('m').value);
var formSeconds = (formHour * 3600) + (formMin * 60);
return formSeconds - currSecs;
}
window.onload = function() {
var scheduleTimerButton = document.getElementById('scheduleTimer');
scheduleTimerButton.addEventListener('click', function() {
var secRemaining = getTimeoutSec();
setTimeout(wakeup, secRemaining * 1000);
}, false);
};
Link to CodePen
Here is an example function
function scheduleAlarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
alert("Successfully scheduled alram!");
setInterval(function(){
var date = new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
if (h == hours && m == minutes && t == ampm){
alert("Time to go to school, wake up!")
}
}, 5000); // will run every 5 seconds
}
Demo: CodePen
I'm trying to create a stopwatch with miliseconds which is as accurate as possible.
Of course the browser/server/cpu or whatever will need more than 1 ms to execute the function and display the digit on the watch. So I thought i want to reset the ms to 0 each time a second goes up.
jQuery code looks like this.
(function($) {
$.fn.stopwatch = function() {
// The Element where the HTML code is added
var clock = $(this);
var timestamprunningms;
var timestampstartms;
var milliseconds = 0;
// Predefinition of the timestamprunningseconds variable
var timestamprunningseconds;
var display = clock.find("#display");
var time = clock.find("#time");
// Predefinition of the seconds variable
// Value 0 because it is used to define
// The timestampstartseconds variable in the click-event
var seconds = 0;
// Predefinition for the timestampstartseconds variable
var timestampstartseconds;
// Predefinition for the timer variable
var timer;
// Time Variables
var h = clock.find("#h");
var m = clock.find("#m");
var s = clock.find("#s");
var ms = clock.find("#ms");
// Button Variables
var resetlog = clock.find("#resetlog")
var showms = clock.find("#showms")
var hidems = clock.find("#hidems")
var start = clock.find("#start");
var pause = clock.find("#pause");
var reset = clock.find("#reset");
var log = clock.find("#log");
ms.hide();
resetlog.click(function (){
time.html("");
});
// Hides the pause and hidems Button
pause.hide();
hidems.hide();
// Triggered by clicking the start button
start.click(function() {
// Hides the start and shows the pause button
start.hide(),
pause.show(),
// Defines the value of timestampstartseconds or saves it
// if there is a value in seconds
timestampstartseconds = Math.round(new Date().getTime() / 1000) - seconds;
timestampstartms = new Date().getTime() - milliseconds;
timer = setInterval(do_time, 20);
});
// Triggered by clicking the pause button
pause.click(function() {
// Resets the interval in which the do_time function occurs
clearInterval(timer),
// Hides the pause and shows the start button
pause.hide(),
start.show(),
timer = 0;
});
// Triggered by clicking the reset button
reset.click(function() {
// Resets the interval in which the do_time function occurs
clearInterval(timer),
// Resets the value of the display
h.html("00"),
m.html("00"),
s.html("00"),
ms.html("000")
// Hides the pause and shows the start button
pause.hide(),
start.show();
seconds = 0;
});
log.click(function() {
time.append("<li>" + display.text() + "</li>");
});
// The function for calculating the seconds/minutes/hours
showms.click(function() {
showms.hide();
hidems.show();
ms.show();
});
hidems.click(function() {
hidems.hide();
showms.show();
ms.hide();
});
function do_time() {
// Timestamp that refreshes everytime the function is executed
timestamprunningseconds = Math.round(new Date().getTime() / 1000);
timestamprunningms = new Date().getTime();
// The actual seconds that are going to be displayed
milliseconds = timestamprunningms - timestampstartms;
seconds = timestamprunningseconds - timestampstartseconds;
// Value of the display
var hour = parseFloat(h.text());
var minute = parseFloat(m.text());
if (milliseconds > 999) {
milliseconds = 0;
timestampstartms = new Date().getTime();
}
// Reset seconds display and add a minute every time 60 seconds pass
if (seconds > 59) {
seconds = 0;
timestampstartseconds = Math.round(new Date().getTime() / 1000);
minute++;
}
// Reset minute display and add an hour every time 60 minutes pass
if (minute > 59) {
minute = 0;
hour++;
}
// Display value
h.html("0".substring(hour >= 10) + hour);
m.html("0".substring(minute >= 10) + minute);
s.html("0".substring(seconds >= 10) + seconds.toString());
ms.html(":" + "0".substring(milliseconds >= 100) +"0".substring(milliseconds >= 10) + milliseconds.toString());
};
};
})(jQuery);
As I already said, my goal is to reset the millisecond timer every time a second goes up. (the seconds are accurate, the milliseconds aren't).
would that be something like this?:
while (seconds++) {
milliseconds = 0;
timestampstartms = new Date().getTime();
}
I'm really new to javascript/jQuery and programming in general so it would be very nice if you could help me with this problem and maybe give a little feedback so I can improve.
Ok I found a solution: i just added a variable which is like a timestamp of the current second. It has a default value of 0 and goes 1 up if the seconds that is used in the display is greater than the second timestamp.
looks a bit like this: var secondnow = 0; (on top of the jQuery function)
and this is how it's used
if (seconds > secondnow) {
milliseconds = 0;
secondnow++;
timestampstartms = new Date().getTime();
console.log(secondnow);
}
(in the function do_time)
I want to validate start time and end time selected using timepicker which is in 12 hr format. The end time should be greater than the start time. I used an if statement but when the test is using values such as 8:00 AM as start time and 1:00 PM as end time, it is not working. What can I do to solve this problem. Someone please help me with this. I am stuck with this since yesterday. I want just time ,i don't need date.
$("#dateTimeAddButton").click(function ()
{
var Date=$('#myDatePickerId').val()
var startTime = $('#i').val();
var endTime = $('#i1').val();
if (startTime > endTime)
{
alert('End time always greater then start time.');
}
});
First convert to lowest denominational (minute here). Then compare it.
st = minFromMidnight(startTime);
et = minFromMidnight(endTime);
if(st>et){
alert("End time must be greater than start time");
}
function minFromMidnight(tm){
var ampm= tm.substr(-2)
var clk = tm.substr(0, 5);
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i))? 12: 0;
return h*60+m;
}
please try that below code in case you have length of time more than 6 char like 10:00am instead of 9:00am will throw error above code.
I did minor changes in above code and it worked like charm for me.
$('#btnSubmit').on('click', function () {
var startTime = $('#txtJobStartTime').val();
var endTime = $('#txtJobEndTime').val();
var st = minFromMidnight(startTime);
var et = minFromMidnight(endTime);
if (st > et) {
alert('End time always greater then start time.');
return false;
}
function minFromMidnight(tm) {
var ampm = tm.substr(-2);
var clk;
if (tm.length <= 6) {
clk = tm.substr(0, 4);
} else {
clk = tm.substr(0, 5);
}
var m = parseInt(clk.match(/\d+$/)[0], 10);
var h = parseInt(clk.match(/^\d+/)[0], 10);
h += (ampm.match(/pm/i)) ? 12 : 0;
return h * 60 + m;
}
});
What I am currently doing is setting up a calendar feature, but when the user selects the date, and then the TIME the event starts (ie startTime = 00:10:00am), that it will then pre-populate the second field (ie: endTime = 00:10:30am).
So I thought maybe the best route would be when you select your time, jQuery would just select the NEXT statement and pick up the 15 minute interval or something of this nature.
I have this code that works to select the exact same time, but that doesn't work well for scheduling obviously, if you select 10am, you don't want your end time to be 10am, you want it to be 10:30am
This is what I have so far, but like I say this just currently selects the same time.
$('.startTime').change(function() {
var startTime = $(this).val();
$('.endTime').val(function() {
return startTime;
});
});
Any guidance would be appreciated.
You'd need to convert startTime into a proper js Date object, then do something like this. If you're using a JS framework, there might already be some utils in place to do this.
This is what works, I don't know if it is efficient or not, but I got this to work. If there is a better answer, I'm all ears.
$('.startTime').change(function() {
var startTime = $(this).val();
var hours = startTime.split(":")[0]; // Hours
var minutes = startTime.split(":")[1]; // Minutes
var seconds = startTime.split(":")[2]; // Seconds
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
var newTime = new Date('0', '0', '0', hours, minutes, seconds, '0');
//alert(newTime.getMinutes());
if(newTime.getMinutes() == '15' || newTime.getMinutes() == '00') {
finalTime = newTime.setMinutes(newTime.getMinutes() + 15);
} else if (newTime.getMinutes() == '30') {
finalTime = newTime.setMinutes(newTime.getMinutes() + 15);
} else if (newTime.getMinutes() == '45') {
finalTime = newTime.setHours(newTime.getHours() + 1, 0);
}
if(newTime.getHours() < 10) {
newHours = '0'+ newTime.getHours();
} else {
newHours = newTime.getHours();
}
if(newTime.getMinutes() < 10) {
newMinutes = '0'+ newTime.getMinutes();
} else {
newMinutes = newTime.getMinutes();
}
if(newTime.getSeconds() < 10) {
newSeconds = '0'+ newTime.getSeconds();
} else {
newSeconds = newTime.getSeconds();
}
var adjustTime = newHours +":"+ newMinutes +":"+ newSeconds;
$('.endTime').val(function() {
return adjustTime;
});
});