I need to know how to set 2 time intervals for the same function?I mean that, now i have set timeinterval of 1 sec to continuously monitor the output of server file.If the output of server file is 0,then color of extension icon changes and it shows a notification.Now the problem is that i have written both these functionalities in the same function.So as i have set time interval for 1 sec and call that function,the notification shows every 1 sec and the color of icon also changes every 1 sec based on server output,which is fine.Now what I need is that i need to change the color every 1 sec.but i need to show notification only every 5 min.can you please help me.i have posted my background.js.can you please help me?
here is my background.js
var myNotificationID = null;
var oldChromeVersion = !chrome.runtime;
var interval = 5 * 60 * 1000; // 5 minutes in milliseconds
var lastNotification = 0;
setInterval(function() {
updateIcon();
}, 1000);
function getGmailUrl() {
return "http://calpinemate.com/";
}
function isGmailUrl(url) {
return url.indexOf(getGmailUrl()) == 0;
}
function onInit() {
updateIcon();
if (!oldChromeVersion) {
chrome.alarms.create('watchdog',{periodInMinutes:5,delayInMinutes: 0});
}
}
function onAlarm(alarm) {
if (alarm && alarm.name == 'watchdog') {
onWatchdog();
}
else {
updateIcon();
}
function onWatchdog() {
chrome.alarms.get('refresh', function(alarm) {
if (alarm) {
console.log('Refresh alarm exists. Yay.');
}
else {
updateIcon();
}
});
}
if (oldChromeVersion) {
updateIcon();
onInit();
}
else {
chrome.runtime.onInstalled.addListener(onInit);
chrome.alarms.onAlarm.addListener(onAlarm);
}
function updateIcon(){
if(localStorage.username){
var urlPrefix = 'http://www.calpinemate.com/employees/attendanceStatus/';
var urlSuffix = '/2';
var req = new XMLHttpRequest();
req.addEventListener("readystatechange", function() {
if (req.readyState == 4) {
if (req.status == 200) {
var item=req.responseText;
if(item==1){
chrome.browserAction.setIcon({path:"calpine_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
chrome.notifications.clear('id1', function(){});
}
else{
chrome.browserAction.setIcon({path:"calpine_not_logged_in.png"});
chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
chrome.browserAction.setBadgeText({text:""});
var now = new Date().getTime();
if (now - lastNotification > interval) {
chrome.notifications.create(
'id1',{
type: 'basic',
iconUrl: '/calpine_not_logged_in.png',
title: 'Warning : Attendance',
message: 'Please mark your Attendance !',
buttons: [{ title: 'Mark',
iconUrl: '/tick.jpg'
},{ title: 'Ignore',
iconUrl: '/cross.jpg'}],
priority: 0},
function(id) { myNotificationID = id;}
);
}
}
}
else {
alert("ERROR: status code " + req.status);
}
}
});
var url = urlPrefix + encodeURIComponent(localStorage.username) + urlSuffix;
req.open("GET", url);
req.send(null);
}
}
onInit();
One possible approach is to keep track of the time when the last notification was displayed and always check if 5 minutes have passed since. E.g.:
/* Put these 2 lines at the very top of your script */
var interval = 5 * 60 * 1000; // 5 minutes in milliseconds
var lastNotification = 0;
Then, inside the updateIcon() function, replace this line:
chrome.notifications.create(...);
with these lines:
var now = new Date().getTime();
if (now - lastNotification > interval) {
lastNotification = now;
chrome.notifications.create(...);
}
The above piece of code will make sure the notification is created only if 5 minutes have passed since the last time a notification was created. It will also update the lastNotification variable with the present time.
Have this code, which runs functionA every 60 seconds, and in between functionB
var launchTime = undefined;
function Launcher() {
if (undefined == launchTime) {
launchTime = new Date();
}
nowTime = new Date();
diff = (nowTime.getTime() - launchTime.getTime()) / 1000;
if (diff % 60 == 0 and diff > 0) { // 60 seconds have passed
functionA();
} else { // 1 second has passed
functionB();
}
}
function functionA() {
}
function functionB() {
}
setInterval(function() { Launcher(); }, 1000);
Related
So basically when I switch tabs, the countdown timer on a specific page just stops counting down and resumes when you return to the tab. Is there anyway to mitigate that so that it counts in the background or it accounts for the time you spend on another tab?
This is basically what I have for js:
document.getElementById('timer').innerHTML =
05 + ":" + 01;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
} else if (m == 0 && s == 0) {
location.reload();
}
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec};
if (sec < 0) {sec = "59"};
return sec;
}
Any ideas whether the time could be done server side or something so that it can't be modified client side? If not, then whatever, but mainly just want to figure out how to make the countdown still work (or account for the time spent) when on another tab.
We can store the variable m and s values either globally or use the local storage to set the values after setting the inner HTML and get the stored values back whenever tabs were switched as:
Set values:
window.localStorage.setItem('minutes', m.toString()); //same for the seconds
Get values:
window.localStorage.getItem('minutes'); //same for the seconds
Hope this answers your questions.
Just a simple solution:
Add this piece of code.
<html>
<head>
<script>
(function() {
var $momentum;
function createWorker() {
var containerFunction = function() {
var idMap = {};
self.onmessage = function(e) {
if (e.data.type === 'setInterval') {
idMap[e.data.id] = setInterval(function() {
self.postMessage({
type: 'fire',
id: e.data.id
});
}, e.data.delay);
} else if (e.data.type === 'clearInterval') {
clearInterval(idMap[e.data.id]);
delete idMap[e.data.id];
} else if (e.data.type === 'setTimeout') {
idMap[e.data.id] = setTimeout(function() {
self.postMessage({
type: 'fire',
id: e.data.id
});
// remove reference to this timeout after is finished
delete idMap[e.data.id];
}, e.data.delay);
} else if (e.data.type === 'clearCallback') {
clearTimeout(idMap[e.data.id]);
delete idMap[e.data.id];
}
};
};
return new Worker(URL.createObjectURL(new Blob([
'(',
containerFunction.toString(),
')();'
], {
type: 'application/javascript'
})));
}
$momentum = {
worker: createWorker(),
idToCallback: {},
currentId: 0
};
function generateId() {
return $momentum.currentId++;
}
function patchedSetInterval(callback, delay) {
var intervalId = generateId();
$momentum.idToCallback[intervalId] = callback;
$momentum.worker.postMessage({
type: 'setInterval',
delay: delay,
id: intervalId
});
return intervalId;
}
function patchedClearInterval(intervalId) {
$momentum.worker.postMessage({
type: 'clearInterval',
id: intervalId
});
delete $momentum.idToCallback[intervalId];
}
function patchedSetTimeout(callback, delay) {
var intervalId = generateId();
$momentum.idToCallback[intervalId] = function() {
callback();
delete $momentum.idToCallback[intervalId];
};
$momentum.worker.postMessage({
type: 'setTimeout',
delay: delay,
id: intervalId
});
return intervalId;
}
function patchedClearTimeout(intervalId) {
$momentum.worker.postMessage({
type: 'clearInterval',
id: intervalId
});
delete $momentum.idToCallback[intervalId];
}
$momentum.worker.onmessage = function(e) {
if (e.data.type === 'fire') {
$momentum.idToCallback[e.data.id]();
}
};
window.$momentum = $momentum;
window.setInterval = patchedSetInterval;
window.clearInterval = patchedClearInterval;
window.setTimeout = patchedSetTimeout;
window.clearTimeout = patchedClearTimeout;
})();
</script>
</head>
</html>
Hi please help how can i add timezone the depends on the current time of my pc or mobile. this code is for my landing page. Thanks
Here is my code..
// Create Countdown
var Countdown = {
// Backbone-like structure
$el: $('.countdown'),
// Params
countdown_interval: null,
total_seconds : 0,
// Initialize the countdown
init: function() {
// DOM
this.$ = {
days : this.$el.find('.bloc-time.days .figure'),
hours : this.$el.find('.bloc-time.hours .figure'),
minutes: this.$el.find('.bloc-time.min .figure'),
seconds: this.$el.find('.bloc-time.sec .figure')
};
// Init countdown values
this.values = {
days : this.$.days.parent().attr('data-init-value'),
hours : this.$.hours.parent().attr('data-init-value'),
minutes: this.$.minutes.parent().attr('data-init-value'),
seconds: this.$.seconds.parent().attr('data-init-value'),
};
// Initialize total seconds
this.total_seconds = this.values.days * 60 * 60 * 60 + (this.values.hours * 60 * 60) + (this.values.minutes * 60) + this.values.seconds;
// Animate countdown to the end
this.count();
},
count: function() {
var that = this,
$day_1 = this.$.days.eq(0),
$day_2 = this.$.days.eq(1),
$hour_1 = this.$.hours.eq(0),
$hour_2 = this.$.hours.eq(1),
$min_1 = this.$.minutes.eq(0),
$min_2 = this.$.minutes.eq(1),
$sec_1 = this.$.seconds.eq(0),
$sec_2 = this.$.seconds.eq(1);
this.countdown_interval = setInterval(function() {
if(that.total_seconds > 0) {
--that.values.seconds;
if(that.values.minutes >= 0 && that.values.seconds < 0) {
that.values.seconds = 59;
--that.values.minutes;
}
if(that.values.hours >= 0 && that.values.minutes < 0) {
that.values.minutes = 59;
--that.values.hours;
}
if(that.values.days >= 0 && that.values.hours < 0) {
that.values.hours = 24;
--that.values.days;
}
// Update DOM values
// Days
that.checkHour(that.values.days, $day_1, $day_2);
// Hours
that.checkHour(that.values.hours, $hour_1, $hour_2);
// Minutes
that.checkHour(that.values.minutes, $min_1, $min_2);
// Seconds
that.checkHour(that.values.seconds, $sec_1, $sec_2);
--that.total_seconds;
}
else {
clearInterval(that.countdown_interval);
document.getElementsByClassName('countdown')[0].style.visibility = 'hidden';
document.getElementsByClassName("countdown-ex")[0].innerHTML = "EXPIRED!";
}
}, 1000);
},
animateFigure: function($el, value) {
var that = this,
$top = $el.find('.top'),
$bottom = $el.find('.bottom'),
$back_top = $el.find('.top-back'),
$back_bottom = $el.find('.bottom-back');
// Before we begin, change the back value
$back_top.find('span').html(value);
// Also change the back bottom value
$back_bottom.find('span').html(value);
// Then animate
TweenMax.to($top, 0.8, {
rotationX : '-180deg',
transformPerspective: 300,
ease : Quart.easeOut,
onComplete : function() {
$top.html(value);
$bottom.html(value);
TweenMax.set($top, { rotationX: 0 });
}
});
TweenMax.to($back_top, 0.8, {
rotationX : 0,
transformPerspective: 300,
ease : Quart.easeOut,
clearProps : 'all'
});
},
checkHour: function(value, $el_1, $el_2) {
var val_1 = value.toString().charAt(0),
val_2 = value.toString().charAt(1),
fig_1_value = $el_1.find('.top').html(),
fig_2_value = $el_2.find('.top').html();
if(value >= 10) {
// Animate only if the figure has changed
if(fig_1_value !== val_1) this.animateFigure($el_1, val_1);
if(fig_2_value !== val_2) this.animateFigure($el_2, val_2);
}
else {
// If we are under 10, replace first figure with 0
if(fig_1_value !== '0') this.animateFigure($el_1, 0);
if(fig_2_value !== val_1) this.animateFigure($el_2, val_1);
}
}
};
// Let's go !
Countdown.init();
Use moment.js with the moment-timezone add on (link), which supports time zone guessing with
moment.tz.guess().
If you can guarantee your users are running a browser that supports the brand new ECMAScript Internationalization API, you can get the user's time zone like this:
Intl.DateTimeFormat().resolvedOptions().timeZone
Reference: Support for ECMAScript Internationalization API
I'm trying to write a 3 second countdown function in JavaScript. The start of the countdown is set by the server so I have setInterval function which calls an ajax function which runs a script on the server to see if it is ready to start the countdown. If the countdown is set, the data returned is that the countdown is ready and will start in a specified number of milliseconds.
I've got the following function which, if I step through I can see the screen updating step by step. However, when I simply run the script it updates everything in bulk. I do not understand why?
$.ajax({
url : "/check_countdown/", // the endpoint
type : "GET", // http method
data : { info : info }, // data sent with the post request
// handle a successful response
success : function(json) {
console.log(json);
if (json.ready == 'True') {
// if we have a start_time then we get ready for the count down
console.log("Countdown ready to start!"); // sanity check
// stop pinging the server
clearInterval(countdownInterval);
// clear screen
$('#holdingImage').hide();
// show countdown block
$('#countdownText').show();
startTime = new Date().getTime() + json.milliseconds;
nowTime = new Date().getTime();
console.log("Every ", nowTime, startTime);
while (nowTime < startTime) {
nowTime = new Date().getTime();
}
$('#countdownText').html("<h1>Three</h1>");
startTime = startTime + 1000;
console.log("Second ", nowTime, startTime);
while (nowTime < startTime) {
nowTime = new Date().getTime();
}
$('#countdownText').html("<h1>Two</h1>");
startTime = startTime + 1000;
console.log("Counts ", nowTime, startTime);
while (nowTime < startTime) {
nowTime = new Date().getTime();
}
$('#countdownText').html("<h1>One</h1>");
} else {
console.log("Countdown NOT ready to start!"); // another sanity check
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
I figure a second (1000 milliseconds) between updates should be enough?
$.ajax({
url : "/check_countdown/", // the endpoint
type : "GET", // http method
data : { info : info }, // data sent with the post request
async: false, //<---- Add this
....
only Add (async: false)
This is the solution that I came up with. I'm not convinced by its efficacy but ...
I changed the success function to:
success : function(json) {
console.log(json);
if (json.ready == 'True') {
// if we have a start_time then we get ready for the count down
console.log("Countdown ready to start!"); // sanity check
console.log(json);
// stop pinging the server
clearInterval(countdownInterval);
// clear screen
$('#holdingImage').hide();
// show countdown block
$('#countdownText').show();
startTime = new Date().getTime() + json.milliseconds;
nowTime = new Date().getTime();
while (nowTime < startTime) {
nowTime = new Date().getTime();
}
startCountdown();
}
I added a new function called startCountdown() which is:
function startCountdown () {
var display1 = document.querySelector('#countdownText'),
startTime = 5,
remainingTime = startTime,
timer = new CountDownTimer(startTime);
timer.onTick(format1).start();
function format1(minutes, seconds) {
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display1.textContent = seconds;
remainingTime = parseInt(minutes) * 60 + parseInt(seconds);
if ((minutes=="00") && (seconds=="00")){
console.log("time expired!"); // sanity check
}
}
}
And then I used this timer.js script which I had from elsewhere (I do not know where I got it so cannot credit the author - sorry)
function CountDownTimer(duration, granularity) {
this.duration = duration;
this.granularity = granularity || 1000;
this.tickFtns = [];
this.running = false;
}
CountDownTimer.prototype.start = function() {
if (this.running) {
return;
}
this.running = true;
var start = Date.now(),
that = this,
diff, obj;
(function timer() {
diff = that.duration - (((Date.now() - start) / 1000) | 0);
if (diff > 0) {
setTimeout(timer, that.granularity);
} else {
diff = 0;
that.running = false;
}
obj = CountDownTimer.parse(diff);
that.tickFtns.forEach(function(ftn) {
ftn.call(this, obj.minutes, obj.seconds);
}, that);
}());
};
CountDownTimer.prototype.onTick = function(ftn) {
if (typeof ftn === 'function') {
this.tickFtns.push(ftn);
}
return this;
};
CountDownTimer.prototype.expired = function() {
return !this.running;
};
CountDownTimer.parse = function(seconds) {
return {
'minutes': (seconds / 60) | 0,
'seconds': (seconds % 60) | 0
};
};
CountDownTimer.prototype.stop = function() {
this.running = false;
};
All in, it gives me my desired result
I have a JavaScript Countdown and I want it to redirect to another site when the countdown ends.
How can I do that?
Code:
(function ( $ ) {
"use strict";
$.fn.countdownTimer = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
endTime: new Date()
}, options );
var $this = $(this);
var $seconds = $this.find(".time.seconds");
var $minutes = $this.find(".time.minutes");
var $hours = $this.find(".time.hours");
var $days = $this.find(".time.days");
var seconds = 0;
var minutes = 0;
var days = 0;
var hours = 0;
var switchCountdownValue = function ($obj, val) {
// Add leading zero
var s = val+"";
while (s.length < 2) s = "0" + s;
if(Modernizr.cssanimations) {
// Fade out previous
var prev = $obj.find(".value").addClass("fadeOutDown").addClass("animated");
// Add next value
var next = $("<div class='value'>" + s + "</div>");
$obj.prepend(next);
// Fade in next value
next.addClass("fadeInDown").addClass("animated");
// Remove from DOM on animation end
// Fix for Safari (if window is not active, then webkitAnimationEnd doesn't fire, so delete it on timeout)
var to = setTimeout(function(){ prev.remove() }, 200);
prev.one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
prev.remove();
clearTimeout(to);
});
} else {
// Remove previous value
var prev = $obj.find(".value").remove();
// Add next value
var next = $("<div class='value'>" + s + "</div>");
$obj.prepend(next);
}
}
var timerId = countdown(settings.endTime,
function(ts) {
if(seconds != ts.seconds) {
switchCountdownValue($seconds, ts.seconds);
seconds = ts.seconds;
}
if(minutes != ts.minutes) {
switchCountdownValue($minutes, ts.minutes);
minutes = ts.minutes;
}
if(hours != ts.hours) {
switchCountdownValue($hours, ts.hours);
hours = ts.hours;
}
if(days != ts.days) {
switchCountdownValue($days, ts.days);
days = ts.days;
}
},
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS);
return this;
};}( jQuery ));
HTML:
<script type="text/javascript">
$().ready(function(){
$(".countdown").countdownTimer({
endTime: new Date("May 13, 2016 20:00:00")
});
$("#notifyMe").notifyMe();
$("#bg-canvas").bezierCanvas({
maxStyles: 1,
maxLines: 50,
lineSpacing: .07,
spacingVariation: .07,
colorBase: {r: 120,g: 100,b: 220},
colorVariation: {r: 50, g: 50, b: 30},
moveCenterX: 0,
moveCenterY: 0,
delayVariation: 3,
globalAlpha: 0.4,
globalSpeed:30,
});
$().ready(function(){
$(".overlap .more").click(function(e){
e.preventDefault();
$("body,html").animate({scrollTop: $(window).height()});
});
});
});
</script>
C&P Code from internet:
http://pastebin.com/CvYNBSED
The Countdown is working perfectly, but I want a redirect when the Countdown ends.
Edit:
Thanks for helping but my problem is, how can I make the if question or how can I check when the countdown has finished?
I know how to make a redirect but I dont know how to check if the countdown is finished.
How to redirect to another webpage in JavaScript/jQuery?
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
as long as your countdown is working, as you said.
Edit.
try the check here:
var timerId = countdown(settings.endTime,
function(ts) {
if(seconds != ts.seconds) {
switchCountdownValue($seconds, ts.seconds);
seconds = ts.seconds;
}
if(minutes != ts.minutes) {
switchCountdownValue($minutes, ts.minutes);
minutes = ts.minutes;
}
if(hours != ts.hours) {
switchCountdownValue($hours, ts.hours);
hours = ts.hours;
}
if(days != ts.days) {
switchCountdownValue($days, ts.days);
days = ts.days;
}
// maybe this will work.
// I didn't check your countdown library because it's minified / uglified
if(days == 0 && hours == 0 && minutes == 0 && seconds == 0){
//redirect here
}
},
countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS);
How about extending your countdownTimer class to add a onDone function to be executed upon completion of the countdown?
...
var settings = $.extend({
endTime: new Date(),
onDone: function () {
window.location.href('http://www.google.com')
}
}, options );
...
Then have your component execute that method when the countdown finishes:
...
prev.one('webkitAnimationEnd ...', function(){
if (settings.onDone) {
settings.onDone();
}
});
...
Just a thought, but to simply answer the question of redirect, then #nonsensei's should suffice.
I'm working on a little "web app" for a quiz.
Each slide has got a certain amount of time to be answered (or 0 to infinite time).
I find JS here to do the countdown:
function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {},
counterEnd = options.onCounterEnd || function () {};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, 1000);
};
this.stop = function () {
clearInterval(timer);
};
}
var myCounter = new Countdown({
seconds: timetogo, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogo - sec;
$('.progress-bar').width(((elapsed / timetogo) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
//alert('counter ended!');
} // final action
});
myCounter.start();
I made a jsfiddle here :
https://jsfiddle.net/mitchum/kz2400cc/2/
But i am having trouble when you go to the next slide, the progress bar "bump".
after looking into "live source panel from chrome" I saw it's like the first "counter" is not stopped and still runs.
Do you have any tips or hint to help me to solve my bug ?
Thanks
You must pay attention to the scope of the variables. I change the "var myCounter" under document ready in "var myCounterFirst". Check the updated JSFiddle.
var timetogoFirst = $('.current').attr("data-time");
var myCounterFirst = new Countdown({
seconds: timetogoFirst, // number of seconds to count down
onUpdateStatus: function (sec) {
elapsed = timetogoFirst - sec;
$('.progress-bar').width(((elapsed / timetogoFirst) * 100) + "%");
}, // callback for each second
onCounterEnd: function () {
alert('counter ended!');
} // final action
});
myCounterFirst.start();