Skip to content

Instantly share code, notes, and snippets.

@inbn
Last active January 28, 2016 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inbn/5da38776edc188ecbca4 to your computer and use it in GitHub Desktop.
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
<!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