Last active
January 28, 2016 19:46
-
-
Save inbn/5da38776edc188ecbca4 to your computer and use it in GitHub Desktop.
Schedule an event at a specific time of the day in JavaScript based on date and time input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Schedule event at specific time</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script> | |
</head> | |
<body> | |
<label for="date">Date</label> | |
<input type="date" id="date" /> | |
<label for="time">Time</label> | |
<input type="time" id="time" /> | |
<button onclick="scheduleEvent()">Schedule Alert</button> | |
<script> | |
var dateInput; | |
var timeInput; | |
function init() { | |
dateInput = document.getElementById('date'); | |
timeInput = document.getElementById('time'); | |
dateInput.value = moment(new Date()).format('YYYY-MM-DD'); | |
timeInput.value = moment(new Date()).format('HH:mm:ss'); | |
} | |
function scheduleEvent() { | |
var date = dateInput.value; | |
var time = timeInput.value; | |
var currentUnixTime = moment().unix(); | |
var scheduledUnixTime = moment(date + ' ' + time).unix(); | |
var remainingTime = scheduledUnixTime - currentUnixTime; | |
if (remainingTime < 0) { | |
alert('You can\'t schedule something in the past'); | |
} else { | |
setTimeout(function(){ alert("It's time") }, remainingTime * 1000); | |
} | |
} | |
init(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment