Support
Quality
Security
License
Reuse
kandi has reviewed AlarmClock and discovered the below as its top functions. This is intended to give you an instant insight into AlarmClock implemented functionality, and help decide if they suit your requirements.
Steventrigg.com Alarm Clock Tutorial
JS Alarmclock needs adjustment
setAlarmTime("{{ js_time }}");
setAlarm()
const display = document.getElementById('clock');
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
audio.loop = true;
let alarmTime = null;
let alarmTimeout = null;
function updateTime() {
const date = new Date();
const hour = formatTime(date.getHours());
const minutes = formatTime(date.getMinutes());
const seconds = formatTime(date.getSeconds());
display.innerText = `${hour} : ${minutes} : ${seconds}`
}
function formatTime(time) {
if (time < 10) {
return '0' + time;
}
return time;
}
function setAlarmTime(value) {
alarmTime = value;
}
function setAlarm() {
if (alarmTime) {
const current = new Date();
const timeToAlarm = new Date(alarmTime);
console.log(timeToAlarm)
if (timeToAlarm > current) {
const timeout = timeToAlarm.getTime() - current.getTime();
alarmTimeout = setTimeout(() => audio.play(), timeout);
setTimeout(clearAlarm, timeout + 5000);
}
else { console.log("time has passed") }
}
}
function clearAlarm() {
audio.pause();
if (alarmTimeout) {
clearTimeout(alarmTimeout);
console.log("Cleared");
}
}
setAlarmTime("2022-03-29T12:23"); // "{{ js_time }}";
// debug
let d = new Date()
d.setSeconds(d.getSeconds() + 10)
setAlarmTime(d.toString())
// end debug
setAlarm()
setInterval(updateTime, 1000);
<div style="width: 100%; display: flex; justify-content: center; ">
<div id="clock"></div>
</div>
-----------------------
setAlarmTime("{{ js_time }}");
setAlarm()
const display = document.getElementById('clock');
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
audio.loop = true;
let alarmTime = null;
let alarmTimeout = null;
function updateTime() {
const date = new Date();
const hour = formatTime(date.getHours());
const minutes = formatTime(date.getMinutes());
const seconds = formatTime(date.getSeconds());
display.innerText = `${hour} : ${minutes} : ${seconds}`
}
function formatTime(time) {
if (time < 10) {
return '0' + time;
}
return time;
}
function setAlarmTime(value) {
alarmTime = value;
}
function setAlarm() {
if (alarmTime) {
const current = new Date();
const timeToAlarm = new Date(alarmTime);
console.log(timeToAlarm)
if (timeToAlarm > current) {
const timeout = timeToAlarm.getTime() - current.getTime();
alarmTimeout = setTimeout(() => audio.play(), timeout);
setTimeout(clearAlarm, timeout + 5000);
}
else { console.log("time has passed") }
}
}
function clearAlarm() {
audio.pause();
if (alarmTimeout) {
clearTimeout(alarmTimeout);
console.log("Cleared");
}
}
setAlarmTime("2022-03-29T12:23"); // "{{ js_time }}";
// debug
let d = new Date()
d.setSeconds(d.getSeconds() + 10)
setAlarmTime(d.toString())
// end debug
setAlarm()
setInterval(updateTime, 1000);
<div style="width: 100%; display: flex; justify-content: center; ">
<div id="clock"></div>
</div>
-----------------------
setAlarmTime("{{ js_time }}");
setAlarm()
const display = document.getElementById('clock');
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
audio.loop = true;
let alarmTime = null;
let alarmTimeout = null;
function updateTime() {
const date = new Date();
const hour = formatTime(date.getHours());
const minutes = formatTime(date.getMinutes());
const seconds = formatTime(date.getSeconds());
display.innerText = `${hour} : ${minutes} : ${seconds}`
}
function formatTime(time) {
if (time < 10) {
return '0' + time;
}
return time;
}
function setAlarmTime(value) {
alarmTime = value;
}
function setAlarm() {
if (alarmTime) {
const current = new Date();
const timeToAlarm = new Date(alarmTime);
console.log(timeToAlarm)
if (timeToAlarm > current) {
const timeout = timeToAlarm.getTime() - current.getTime();
alarmTimeout = setTimeout(() => audio.play(), timeout);
setTimeout(clearAlarm, timeout + 5000);
}
else { console.log("time has passed") }
}
}
function clearAlarm() {
audio.pause();
if (alarmTimeout) {
clearTimeout(alarmTimeout);
console.log("Cleared");
}
}
setAlarmTime("2022-03-29T12:23"); // "{{ js_time }}";
// debug
let d = new Date()
d.setSeconds(d.getSeconds() + 10)
setAlarmTime(d.toString())
// end debug
setAlarm()
setInterval(updateTime, 1000);
<div style="width: 100%; display: flex; justify-content: center; ">
<div id="clock"></div>
</div>
how to pass uncertain parameter to method flutter
class AlarmClock {
bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
}
void reverseWeekdayStatus({
alarmClock,
}) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
...
}
void reverseWeekdayStatus({alarmClock, bool switchSundayState = false}) {
if (switchSundayState) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
}
}
class AlarmClock {
final bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
AlarmClock copyWith({
bool? sundayIsSelected,
}) {
return AlarmClock(
sundayIsSelected: sundayIsSelected ?? this.sundayIsSelected,
);
}
}
-----------------------
class AlarmClock {
bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
}
void reverseWeekdayStatus({
alarmClock,
}) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
...
}
void reverseWeekdayStatus({alarmClock, bool switchSundayState = false}) {
if (switchSundayState) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
}
}
class AlarmClock {
final bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
AlarmClock copyWith({
bool? sundayIsSelected,
}) {
return AlarmClock(
sundayIsSelected: sundayIsSelected ?? this.sundayIsSelected,
);
}
}
-----------------------
class AlarmClock {
bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
}
void reverseWeekdayStatus({
alarmClock,
}) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
...
}
void reverseWeekdayStatus({alarmClock, bool switchSundayState = false}) {
if (switchSundayState) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
}
}
class AlarmClock {
final bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
AlarmClock copyWith({
bool? sundayIsSelected,
}) {
return AlarmClock(
sundayIsSelected: sundayIsSelected ?? this.sundayIsSelected,
);
}
}
-----------------------
class AlarmClock {
bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
}
void reverseWeekdayStatus({
alarmClock,
}) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
...
}
void reverseWeekdayStatus({alarmClock, bool switchSundayState = false}) {
if (switchSundayState) {
alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
}
}
class AlarmClock {
final bool sundayIsSelected;
AlarmClock({
this.sundayIsSelected = false,
});
AlarmClock copyWith({
bool? sundayIsSelected,
}) {
return AlarmClock(
sundayIsSelected: sundayIsSelected ?? this.sundayIsSelected,
);
}
}
The getter 'sundayIsSelected' was called on null. Receiver: null Tried calling: sundayIsSelected
class TimePickerPage extends StatefulWidget {
final AlarmClock alarmClock;
const TimePickerPage({Key? key, required this.alarmClock}) : super(key: key);
@override
_TimePickerPageState createState() => _TimePickerPageState();
}
class _TimePickerPageState extends State<TimePickerPage> {
late bool sundayIsSelected;
@override
void initState() {
sundayIsSelected = widget.alarmClock.sundayIsSelected;
super.initState();
}
@override
Widget build(BuildContext context) {
return Text(sundayIsSelected.toString());
}
}
final alarmClock = AlarmClock(),
....
TimePickerPage(
alarmClock: alarmClock,
),
// or
TimePickerPage(
alarmClock: AlarmClock(),
)
...
-----------------------
class TimePickerPage extends StatefulWidget {
final AlarmClock alarmClock;
const TimePickerPage({Key? key, required this.alarmClock}) : super(key: key);
@override
_TimePickerPageState createState() => _TimePickerPageState();
}
class _TimePickerPageState extends State<TimePickerPage> {
late bool sundayIsSelected;
@override
void initState() {
sundayIsSelected = widget.alarmClock.sundayIsSelected;
super.initState();
}
@override
Widget build(BuildContext context) {
return Text(sundayIsSelected.toString());
}
}
final alarmClock = AlarmClock(),
....
TimePickerPage(
alarmClock: alarmClock,
),
// or
TimePickerPage(
alarmClock: AlarmClock(),
)
...
Countdown does not stop properly
function startTimer() {
let startTime = new Date().getTime();
// If its five minute 5 * 60 * 1000;
let fiveSeconds = 5 * 1000;
let endTime = startTime + fiveSeconds;
var countdown = setInterval(function count() {
let timeLeft = endTime - new Date().getTime();
let minutes = Math.floor((timeLeft / (1000 * 60)) % 60);
let seconds = Math.floor((timeLeft / 1000) % 60);
// Once test is passed do the DOM manipulation
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds === 0)) {
return clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
5:00
</div>
<div class="button center">
<button onclick="startTimer()">Start</button>
</div>
-----------------------
function startTimer() {
let startTime = new Date().getTime();
// If its five minute 5 * 60 * 1000;
let fiveSeconds = 5 * 1000;
let endTime = startTime + fiveSeconds;
var countdown = setInterval(function count() {
let timeLeft = endTime - new Date().getTime();
let minutes = Math.floor((timeLeft / (1000 * 60)) % 60);
let seconds = Math.floor((timeLeft / 1000) % 60);
// Once test is passed do the DOM manipulation
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds === 0)) {
return clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
5:00
</div>
<div class="button center">
<button onclick="startTimer()">Start</button>
</div>
-----------------------
function startTimer() {
let startTime = new Date().getTime();
let fiveMinutes = 5 * 1 * 1000;
let endTime = startTime + fiveMinutes;
var countdown = setInterval(function () {
let timeLeft = endTime - new Date().getTime();
let minutes = timeLeft / (1000 * 60);
minutes = Math.round(minutes);
let seconds = (timeLeft / 1000) % 60;
seconds = Math.round(seconds);
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds <= 0)) {
clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
00:05
</div>
<div class="button center">
<img onclick="startTimer()" img src="img/btn.png" alt="button start" />
</div>
-----------------------
function startTimer() {
let startTime = new Date().getTime();
let fiveMinutes = 5 * 1 * 1000;
let endTime = startTime + fiveMinutes;
var countdown = setInterval(function () {
let timeLeft = endTime - new Date().getTime();
let minutes = timeLeft / (1000 * 60);
minutes = Math.round(minutes);
let seconds = (timeLeft / 1000) % 60;
seconds = Math.round(seconds);
let text = minutes + ':' + seconds;
timer.innerHTML = text;
if ((minutes <= 0) && (seconds <= 0)) {
clearInterval(countdown);
}
}, 1000);
}
<div class="timer center margin-top" id="timer">
00:05
</div>
<div class="button center">
<img onclick="startTimer()" img src="img/btn.png" alt="button start" />
</div>
Attempt to make a timer in python, where is the error?
command = lambda: self.timer()
self.b0 = Button(self.alarm,....,command=lambda: self.timer(self.e0.get()))
def timer(self, time):
time = float(time)
self.l2.configure(text=time)
if time > 0:
time -= 1
self.alarm.after(1000, self.timer, time)
else:
self.l2.configure(text=time)
messagebox.showwarning('Alarm Clock', 'Time\'s up!')
-----------------------
command = lambda: self.timer()
self.b0 = Button(self.alarm,....,command=lambda: self.timer(self.e0.get()))
def timer(self, time):
time = float(time)
self.l2.configure(text=time)
if time > 0:
time -= 1
self.alarm.after(1000, self.timer, time)
else:
self.l2.configure(text=time)
messagebox.showwarning('Alarm Clock', 'Time\'s up!')
-----------------------
from tkinter import *
from tkinter import messagebox
class alarmclock():
def __init__(self):
self.alarm = Tk()
self.l0 = Label(self.alarm, text = '----------- Alarm clock 1 -----------')
self.l1 = Label(self.alarm, text = 'Please type in the time:')
self.e0 = Entry(self.alarm)
self.countdown = StringVar(self.alarm, "")
self.l2 = Label(self.alarm, textvariable=self.countdown)
self.b0 = Button(self.alarm, text = 'Start countdown', command = lambda : self.timer(reset=True))
self.l0.grid(row = 0, column = 0, columnspan = 2)
self.l1.grid(row = 1, column = 0, padx = 10, pady =5)
self.e0.grid(row = 1, column = 1, padx = 10)
self.l2.grid(row = 2, column = 1, padx = 10)
self.b0.grid(row = 3, column = 0, columnspan = 2, pady = 5)
self.alarm.mainloop()
def timer(self, reset=False):
if reset:
self.b = float(self.e0.get())
self.countdown.set(str(self.b))
self.b-=1
if self.b >= 0:
self.alarm.after(1000, self.timer)
else:
messagebox.showwarning('Alarm Clock', 'Time\'s up!')
if __name__ == '__main__':
my_alarm = alarmclock()
-----------------------
import time
from tkinter import messagebox
class PDTkClock(Exception):
__module__ = Exception.__module__
class Timer:
"""
valid parameter ::--
year, month, week, day, hour, minute, second
"""
_value = ("year", 'month', "week", "day", "hour", "minute", "second")
def __init__(self, tk_widget, **kwargs):
self._sec = 0
self.time_over = False
if self._check(**kwargs) and not self.time_over:
for i in kwargs:
if i == "year":
val = kwargs[i]
self._sec += val * 31556952
elif i == "month":
val = kwargs[i]
self._sec += val * 2628000
elif i == "week":
val = kwargs[i]
self._sec += val * 604800
elif i == "day":
val = kwargs[i]
self._sec += val * 86400
elif i == "hour":
val = kwargs[i]
self._sec += val * 3600
elif i == "minute":
val = kwargs[i]
self._sec += val * 60
elif i == "second":
val = kwargs[i]
self._sec += val * 1
self._time_it(tk_widget, self._sec)
else:
raise PDTkClock(f"kwargs must be {self._value}")
def _time_it(self, tk_widget, sec):
_ = sec
year = sec // 31556952
sec -= year * 31556952
month = sec // 2628000
sec -= month * 2628000
week = sec // 604800
sec -= week * 604800
day = sec // 86400
sec -= day * 86400
hour = sec // 3600
sec -= hour * 3600
minute = sec // 60
sec -= minute * 60
second = sec // 1
get = f"{year}:{month}:{week}:{day}:{hour}:{minute}:{second}"
if _ >=0 and not self.time_over:
tk_widget['text'] = get
tk_widget.update()
tk_widget.after(1000, self._time_it, tk_widget, _ - 1)
else:
messagebox.showwarning('Alarm Clock', 'Time\'s up!')
def _check(self, **kwargs):
ch = []
for i in kwargs:
if i in self._value:
ch.append(True)
else:
ch.append(False)
break
return all(ch)
from tkinter import Tk, Label
r = Tk()
l1 = Label(r)
l1.pack()
Timer(l2, second=10, minute=0)
r.mainloop()
How to containerize a Java application with user-defined reference classes in Docker?
FROM openjdk:9
COPY . /usr/src/myjava
WORKDIR /usr/src/myjava
RUN javac Program.java AlarmClock.java Clock.java
CMD ["java", "Program", "AlarmClock", "Clock"]
How can I roll-over in java?
if (minutes < 0) {
throw new IllegalArgumentException();
}
int hours = minutes/60;
for(int i = 0; i<hours; i++) {
this.theClock.incrementHour();
}
minutes %= 60; // remaining minutes
for(int i = 0; i < minutes; i++) {
this.theClock.incrementMinutes();
}
public void incrementHours(int value) {
this.hour = (this.hour + value) % 24;
}
-----------------------
if (minutes < 0) {
throw new IllegalArgumentException();
}
int hours = minutes/60;
for(int i = 0; i<hours; i++) {
this.theClock.incrementHour();
}
minutes %= 60; // remaining minutes
for(int i = 0; i < minutes; i++) {
this.theClock.incrementMinutes();
}
public void incrementHours(int value) {
this.hour = (this.hour + value) % 24;
}
notify not working on android studio ( API 27, ANDROID 8.1.0)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationManager mNotificationManager =
(NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNNEL_ID,
CHANNEL_NAME, importance);
mChannel.setDescription(CHANNEL_DESC);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400,
300, 200, 400});
mNotificationManager.createNotificationChannel(mChannel);
}
-----------------------
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
showNotification(getApplicationContext(),"This is the title", "This is the body", getIntent());
-----------------------
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
showNotification(getApplicationContext(),"This is the title", "This is the body", getIntent());
intent on kotlin on android studio not working
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
startActivity(Intent(this, diceRoll::class.java))
}
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
val diceRollIntent = Intent(this, diceRoll::class.java) //assigns the intent to a variable which we can use
startActivity(diceRollIntent)
}
-----------------------
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
startActivity(Intent(this, diceRoll::class.java))
}
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
val diceRollIntent = Intent(this, diceRoll::class.java) //assigns the intent to a variable which we can use
startActivity(diceRollIntent)
}
-----------------------
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
startActivity(Intent(this, diceRoll::class.java))
}
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
val diceRollIntent = Intent(this, diceRoll::class.java) //assigns the intent to a variable which we can use
startActivity(diceRollIntent)
}
-----------------------
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
startActivity(Intent(this, diceRoll::class.java))
}
private fun tnxt(){
Intent(this, diceRoll::class.java)
startActivity(intent)
}
private fun tnxt(){
val diceRollIntent = Intent(this, diceRoll::class.java) //assigns the intent to a variable which we can use
startActivity(diceRollIntent)
}
Cannot get packageManagers or Context to pass to classes on functions that worked fine in main. Kotlin
package com.celadian.goodintents
import android.app.Application
import android.content.Context
import android.content.Intent
import android.provider.AlarmClock
class CreateTimer: Application() {
fun startTimer(message: String, seconds: Int, context: Context) {
val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
putExtra(AlarmClock.EXTRA_MESSAGE, message)
putExtra(AlarmClock.EXTRA_LENGTH, seconds)
putExtra(AlarmClock.EXTRA_SKIP_UI, true)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
if (intent.resolveActivity(context.packageManager) != null) {
context.startActivity(intent)
}
}
}
QUESTION
JS Alarmclock needs adjustment
Asked 2022-Mar-29 at 10:24I'm trying to set an alarmclock for the webapp I'm creating with Django. To do so, I followed some tutorials and adjusted the code for my needs and all. It works. My problem is, I want to set the time and date, manually, with the variables I get from Django views (I passed the hour and min variables into my HTML file). Here is my alarm.html file:
{% extends 'mainapp_hf/base.html' %}
{% block content %}
{{ js_hour }}
<div style="width: 100%; display: flex; justify-content: center; ">
<div id="clock"></div>
<script>
const display = document.getElementById('clock');
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
audio.loop = true;
let alarmTime = null;
let alarmTimeout = null;
function updateTime() {
const date = new Date();
const hour = formatTime(date.getHours());
const minutes = formatTime(date.getMinutes());
const seconds = formatTime(date.getSeconds());
display.innerText=`${hour} : ${minutes} : ${seconds}`
}
function formatTime(time) {
if ( time < 10 ) {
return '0' + time;
}
return time;
}
function setAlarmTime(value) {
alarmTime = value;
}
function setAlarm() {
if(alarmTime) {
const current = new Date();
const timeToAlarm = new Date(alarmTime);
if (timeToAlarm > current) {
const timeout = timeToAlarm.getTime() - current.getTime();
alarmTimeout = setTimeout(() => audio.play(), timeout);
setTimeout(clearAlarm, timeout + 5000);
alert( value );
}
}
}
function clearAlarm() {
audio.pause();
if (alarmTimeout) {
clearTimeout(alarmTimeout);
alert("value");
}
}
setAlarmTime
setAlarm
alert( value )
setInterval(updateTime, 1000);
</script>
</div>
{% endblock %}
I'm newborn JS learner. I have no clue how to go further at this point, just to understand and adjust this current code took me hours. For starter, I'm okay to ignore all other variables (like date, minute, second). Can anyone guide me to just to get the realtime hour and then compare it with my django variable {{ js_hour }} (data type is number, and lets say its equal to 15) and if they match, ring the sound (regardless of date or minute).
The variable "value" in setAlarmTime, is the user input that is being submitted via a form, but since I dont want that form anymore, (instead, I want to use my django variables), I didnt include that part of the code here.
The form user normally submits, has HTML input field that has type of "datetime-local". I tried to write my js_hour python variable in this format, like following
views.py
js_hour = "2022-03-29T11:00"
and then adjusted following part:
alarm.html
function setAlarmTime(value) {
alarmTime = {{ js_hour }};
}
Thought this should do the trick. When I dont play around and just get the user input, type of alarmTime is [object HTMLInputElement], and when I replace it with {{ js_hour }}, data type turns into an object. And no alarm rings, code stop working.
Any suggestions?
ANSWER
Answered 2022-Mar-29 at 10:24Just do
setAlarmTime("{{ js_time }}");
setAlarm()
and remove the alerts - you do not have a var called value
const display = document.getElementById('clock');
const audio = new Audio('https://assets.mixkit.co/sfx/preview/mixkit-alarm-digital-clock-beep-989.mp3');
audio.loop = true;
let alarmTime = null;
let alarmTimeout = null;
function updateTime() {
const date = new Date();
const hour = formatTime(date.getHours());
const minutes = formatTime(date.getMinutes());
const seconds = formatTime(date.getSeconds());
display.innerText = `${hour} : ${minutes} : ${seconds}`
}
function formatTime(time) {
if (time < 10) {
return '0' + time;
}
return time;
}
function setAlarmTime(value) {
alarmTime = value;
}
function setAlarm() {
if (alarmTime) {
const current = new Date();
const timeToAlarm = new Date(alarmTime);
console.log(timeToAlarm)
if (timeToAlarm > current) {
const timeout = timeToAlarm.getTime() - current.getTime();
alarmTimeout = setTimeout(() => audio.play(), timeout);
setTimeout(clearAlarm, timeout + 5000);
}
else { console.log("time has passed") }
}
}
function clearAlarm() {
audio.pause();
if (alarmTimeout) {
clearTimeout(alarmTimeout);
console.log("Cleared");
}
}
setAlarmTime("2022-03-29T12:23"); // "{{ js_time }}";
// debug
let d = new Date()
d.setSeconds(d.getSeconds() + 10)
setAlarmTime(d.toString())
// end debug
setAlarm()
setInterval(updateTime, 1000);
<div style="width: 100%; display: flex; justify-content: center; ">
<div id="clock"></div>
</div>
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
Explore Related Topics
Save this library and start creating your kit