Im trying to create an alarm clock, but have run into a little problem.
How do I clear the timer (setInterval) when it can't be accessed from within the 'if statement'? And how do I start it again when the Close button is hit? (see comments in code) Thanks in advance!
var timer = setInterval(displaytime, 1000); function displaytime (){ var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); // FORSØG PÅ ALARM if (hours == hourAlarm && minutes == minuteAlarm) { Ti.API.info('Alarm Aktiv') clearInterval(timer); // NEED TO CLEAR INTERVAL HERE var alertWindow = Titanium.UI.createWindow({ backgroundColor: '#333333', title:'Alarm', barColor:'#C02f25', url:'alarmVindue.js' }); var closeButton = Titanium.UI.createButton({ title:'Luk Vindue', style:Titanium.UI.iPhone.SystemButtonStyle.PLAIN }); alertWindow.setLeftNavButton(closeButton); closeButton.addEventListener('click', function(){ alertWindow.close(); // NEED TO START TIMER AGAIN HERE Ti.API.info('Clicked Close Button') }); alertWindow.open({modal:true}); } else { Ti.API.info('Alarm Inaktiv') } } });
2 Answers
Here, declare timer outside event handler and you need to use setTimeout and clearTimeout as clearInterval is having issues…
Try this code..
var timer; picker.addEventListener('change',function(e) { var d = new Date(e.value); hourAlarm = d.getHours(); minuteAlarm = d.getMinutes(); Ti.API.info(hourAlarm + ":" + minuteAlarm); timer = setTimeout(displaytime, 1000); function displaytime (){ var now = new Date(); var hours = now.getHours(); var minutes = now.getMinutes(); // FORSØG PÅ ALARM if (hours == hourAlarm && minutes == minuteAlarm) { Ti.API.info('Alarm Aktiv') clearTimeout(timer); // NEED TO CLEAR INTERVAL HERE var alertWindow = Titanium.UI.createWindow({ backgroundColor: '#333333', title:'Alarm', barColor:'#C02f25', url:'alarmVindue.js' }); var closeButton = Titanium.UI.createButton({ title:'Luk Vindue', style:Titanium.UI.iPhone.SystemButtonStyle.PLAIN }); alertWindow.setLeftNavButton(closeButton); closeButton.addEventListener('click', function(){ alertWindow.close(); // NEED TO START TIMER AGAIN HERE timer = setTimeout(displaytime, 1000); Ti.API.info('Clicked Close Button') }); alertWindow.open({modal:true}); } else { Ti.API.info('Alarm Inaktiv') } } });Regards
Nikunj
The answer was to move
var d = new Date(e.value); hourAlarm = d.getHours(); minuteAlarm = d.getMinutes();inside the display time function
Your Answer
Think you can help? Login to answer this question!