Body Background based on hour of the day JS - javascript

<script type="javascript">
jQuery(document).ready(function($){
var dt = new Date();
var currentHour = dt.getHours();
$('body').css('background', '#FFF url(https://crystalforums.cf/bk/bk_'+currentHour+'.png) no-repeat center center fixed');
$('body').css('background-size', 'cover');
});
</script>
Hey! I had this script working on a my forum and i tried working it on a my website index, but it seems to not work. They both use the body thingy (I forgot the actual term, it's Saturday and i got a ton of work) so they should effect the body element right? What am i doing wrong, the script suppose to set the background image of the website to a new image based on every hour. Help???
I don't want it to auto update, they cxan refresh. I want so there is one background for every hour.

First...I don't recommend use javascript for this....Your approach needs an user for an hour into your website and in the same page...If you still think in change that you will need use setTimeout function...
My recommendation is using a server side technology for this...

You can use setInterval() with duration set to 5 minutes 60000 * 5 or briefer duration between function calls
$().ready(function() {
var interval, curr;
function handleBackground() {
var dt = new Date();
var currentHour = dt.getHours();
if (!curr || currentHour !== curr) {
curr = currentHour;
$('body').css('background', 'url(https://crystalforums.cf/bk/bk_'
+ currentHour
+ '.png) no-repeat center center fixed');
}
}
// call `handleBackground` to set initial `background` at `body`
handleBackground();
interval = setInterval(handleBackground, 60000 * 5);
});
plnkr http://plnkr.co/edit/5YTPgPgaKbXfYIT0MG3x?p=preview

I don't know JQuery, I always use Java Script :P,
If you want to change background after 5 Minutes you can do this by javascript
<script>
index = 0;
function changeBackground(){
var backColor = ["image.jpg","image2.jpg","image3.jpg","image4.jpg"];
document.body.style.backgroundImage = "url("+backColor[index]+")";
index++;
if(index > (backColor.length) - 1){
index = 0;
}
}
//1000 means 1 second, so for 5 min
// 6,000 X 5 = 30,000
setInterval(changeBackground, 30000);
</script>
Just try this code.

You can use the setInterval() function like this:
function someFunction() {
alert("It's been one hour");
}
setInterval(someFunction, 3600000);
Where the 3600000 is a hour in milliseconds.

Related

is there a way to continue running intervals in javascript even after changing tabs or minimizing the window? [duplicate]

I have a setInterval running a piece of code 30 times a second. This works great, however when I select another tab (so that the tab with my code becomes inactive), the setInterval is set to an idle state for some reason.
I made this simplified test case (http://jsfiddle.net/7f6DX/3/):
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.css("left", a)
}, 1000 / 30);
If you run this code and then switch to another tab, wait a few seconds and go back, the animation continues at the point it was when you switched to the other tab.
So the animation isn't running 30 times a second in case the tab is inactive. This can be confirmed by counting the amount of times the setInterval function is called each second - this will not be 30 but just 1 or 2 if the tab is inactive.
I guess that this is done by design so as to improve system performance, but is there any way to disable this behavior?
It’s actually a disadvantage in my scenario.
On most browsers inactive tabs have low priority execution and this can affect JavaScript timers.
If the values of your transition were calculated using real time elapsed between frames instead fixed increments on each interval, you not only workaround this issue but also can achieve a smother animation by using requestAnimationFrame as it can get up to 60fps if the processor isn't very busy.
Here's a vanilla JavaScript example of an animated property transition using requestAnimationFrame:
var target = document.querySelector('div#target')
var startedAt, duration = 3000
var domain = [-100, window.innerWidth]
var range = domain[1] - domain[0]
function start() {
startedAt = Date.now()
updateTarget(0)
requestAnimationFrame(update)
}
function update() {
let elapsedTime = Date.now() - startedAt
// playback is a value between 0 and 1
// being 0 the start of the animation and 1 its end
let playback = elapsedTime / duration
updateTarget(playback)
if (playback > 0 && playback < 1) {
// Queue the next frame
requestAnimationFrame(update)
} else {
// Wait for a while and restart the animation
setTimeout(start, duration/10)
}
}
function updateTarget(playback) {
// Uncomment the line below to reverse the animation
// playback = 1 - playback
// Update the target properties based on the playback position
let position = domain[0] + (playback * range)
target.style.left = position + 'px'
target.style.top = position + 'px'
target.style.transform = 'scale(' + playback * 3 + ')'
}
start()
body {
overflow: hidden;
}
div {
position: absolute;
white-space: nowrap;
}
<div id="target">...HERE WE GO</div>
For Background Tasks (non-UI related)
#UpTheCreek comment:
Fine for presentation issues, but still
there are some things that you need to keep running.
If you have background tasks that needs to be precisely executed at given intervals, you can use HTML5 Web Workers. Take a look at Möhre's answer below for more details...
CSS vs JS "animations"
This problem and many others could be avoided by using CSS transitions/animations instead of JavaScript based animations which adds a considerable overhead. I'd recommend this jQuery plugin that let's you take benefit from CSS transitions just like the animate() methods.
I ran into the same problem with audio fading and HTML5 player. It got stuck when tab became inactive.
So I found out a WebWorker is allowed to use intervals/timeouts without limitation. I use it to post "ticks" to the main javascript.
WebWorkers Code:
var fading = false;
var interval;
self.addEventListener('message', function(e){
switch (e.data) {
case 'start':
if (!fading){
fading = true;
interval = setInterval(function(){
self.postMessage('tick');
}, 50);
}
break;
case 'stop':
clearInterval(interval);
fading = false;
break;
};
}, false);
Main Javascript:
var player = new Audio();
player.fader = new Worker('js/fader.js');
player.faderPosition = 0.0;
player.faderTargetVolume = 1.0;
player.faderCallback = function(){};
player.fadeTo = function(volume, func){
console.log('fadeTo called');
if (func) this.faderCallback = func;
this.faderTargetVolume = volume;
this.fader.postMessage('start');
}
player.fader.addEventListener('message', function(e){
console.log('fader tick');
if (player.faderTargetVolume > player.volume){
player.faderPosition -= 0.02;
} else {
player.faderPosition += 0.02;
}
var newVolume = Math.pow(player.faderPosition - 1, 2);
if (newVolume > 0.999){
player.volume = newVolume = 1.0;
player.fader.postMessage('stop');
player.faderCallback();
} else if (newVolume < 0.001) {
player.volume = newVolume = 0.0;
player.fader.postMessage('stop');
player.faderCallback();
} else {
player.volume = newVolume;
}
});
There is a solution to use Web Workers (as mentioned before), because they run in separate process and are not slowed down
I've written a tiny script that can be used without changes to your code - it simply overrides functions setTimeout, clearTimeout, setInterval, clearInterval.
Just include it before all your code.
more info here
Both setInterval and requestAnimationFrame don't work when tab is inactive or work but not at the right periods. A solution is to use another source for time events. For example web sockets or web workers are two event sources that work fine while tab is inactive. So no need to move all of your code to a web worker, just use worker as a time event source:
// worker.js
setInterval(function() {
postMessage('');
}, 1000 / 50);
.
var worker = new Worker('worker.js');
var t1 = 0;
worker.onmessage = function() {
var t2 = new Date().getTime();
console.log('fps =', 1000 / (t2 - t1) | 0);
t1 = t2;
}
jsfiddle link of this sample.
Just do this:
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.stop(true,true).css("left", a);
}, 1000 / 30);
Inactive browser tabs buffer some of the setInterval or setTimeout functions.
stop(true,true) will stop all buffered events and execute immediatly only the last animation.
The window.setTimeout() method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
For me it's not important to play audio in the background like for others here, my problem was that I had some animations and they acted like crazy when you were in other tabs and coming back to them. My solution was putting these animations inside if that is preventing inactive tab:
if (!document.hidden){ //your animation code here }
thanks to that my animation was running only if tab was active.
I hope this will help someone with my case.
I think that a best understanding about this problem is in this example: http://jsfiddle.net/TAHDb/
I am doing a simple thing here:
Have a interval of 1 sec and each time hide the first span and move it to last, and show the 2nd span.
If you stay on page it works as it is supposed.
But if you hide the tab for some seconds, when you get back you will see a weired thing.
Its like all events that didn't ucur during the time you were inactive now will ocur all in 1 time. so for some few seconds you will get like X events. they are so quick that its possible to see all 6 spans at once.
So it seams chrome only delays the events, so when you get back all events will occur but all at once...
A pratical application were this ocur iss for a simple slideshow. Imagine the numbers being Images, and if user stay with tab hidden when he came back he will see all imgs floating, Totally mesed.
To fix this use the stop(true,true) like pimvdb told.
THis will clear the event queue.
Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head> and it will patch setInterval and setTimeout with ones that use WebWorker.
Playing an audio file ensures full background Javascript performance for the time being
For me, it was the simplest and least intrusive solution - apart from playing a faint / almost-empty sound, there are no other potential side effects
You can find the details here: https://stackoverflow.com/a/51191818/914546
(From other answers, I see that some people use different properties of the Audio tag, I do wonder whether it's possible to use the Audio tag for full performance, without actually playing something)
I bring here a simple solution for anyone who is trying to get around this problem in a timer function, where as #kbtzr mentioned in another answer we can use the Date object instead of fixed increments to calculate the time that has passed since the beginning, which will work even if you are out from the application's tab.
This is the example HTML.
<body>
<p id="time"></p>
</body>
Then this JavaScript:
let display = document.querySelector('#time')
let interval
let time
function startTimer() {
let initialTime = new Date().getTime()
interval = setInterval(() => {
let now = new Date().getTime()
time = (now - initialTime) + 10
display.innerText = `${Math.floor((time / (60 * 1000)) % 60)}:${Math.floor((time / 1000) % 60)}:${Math.floor((time / 10) % 100)}`
}, 10)
}
startTimer()
That way, even if the interval value is increased for performance reasons of inactive tabs, the calculation made will guarantee the correct time. This is a vanilla code, but I used this logic in my React application, and you can modify it for wherever you need as well.
It is quite old question but I encountered the same issue.
If you run your web on chrome, you could read through this post Background Tabs in Chrome 57.
Basically the interval timer could run if it haven't run out of the timer budget.
The consumption of budget is based on CPU time usage of the task inside timer.
Based on my scenario, I draw video to canvas and transport to WebRTC.
The webrtc video connection would keep updating even the tab is inactive.
However you have to use setInterval instead of requestAnimationFrame but itt is not recommended for UI rendering though.
It would be better to listen visibilityChange event and change render mechenism accordingly.
Besides, you could try what Kaan Soral suggests and it should works based on the documentation.
I modified Lacerda's response, by adding a functioning UI.
I added start/resume/pause/stop actions.
const
timer = document.querySelector('.timer'),
timerDisplay = timer.querySelector('.timer-display'),
toggleAction = timer.querySelector('[data-action="toggle"]'),
stopAction = timer.querySelector('[data-action="stop"]'),
tickRate = 10;
let intervalId, initialTime, pauseTime = 0;
const now = () => new Date().getTime();
const formatTime = (hours, minutes, seconds) =>
[hours, minutes, seconds]
.map(v => `${isNaN(v) ? 0 : v}`.padStart(2, '0'))
.join(':');
const update = () => {
let
time = (now() - initialTime) + 10,
hours = Math.floor((time / (60000)) % 60),
minutes = Math.floor((time / 1000) % 60),
seconds = Math.floor((time / 10) % 100);
timerDisplay.textContent = formatTime(hours, minutes, seconds);
};
const
startTimer = () => {
initialTime = now();
intervalId = setInterval(update, tickRate);
},
resumeTimer = () => {
initialTime = now() - (pauseTime - initialTime);
intervalId = setInterval(update, tickRate);
},
pauseTimer = () => {
clearInterval(intervalId);
intervalId = null;
pauseTime = now();
},
stopTimer = () => {
clearInterval(intervalId);
intervalId = null;
initialTime = undefined;
pauseTime = 0;
},
restartTimer = () => {
stopTimer();
startTimer();
};
const setButtonState = (button, state, text) => {
button.dataset.state = state;
button.textContent = text;
};
const
handleToggle = (e) => {
switch (e.target.dataset.state) {
case 'pause':
setButtonState(e.target, 'resume', 'Resume');
pauseTimer();
break;
case 'resume':
setButtonState(e.target, 'pause', 'Pause');
resumeTimer();
break;
default:
setButtonState(e.target, 'pause', 'Pause');
restartTimer();
}
},
handleStop = (e) => {
stopTimer();
update();
setButtonState(toggleAction, 'initial', 'Start');
};
toggleAction.addEventListener('click', handleToggle);
stopAction.addEventListener('click', handleStop);
update();
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
background: #000;
}
.timer {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.5em;
}
.timer .timer-display {
font-family: monospace;
font-size: 3em;
background: #111;
color: #8F8;
border: thin solid #222;
padding: 0.25em;
}
.timer .timer-actions {
display: flex;
justify-content: center;
gap: 0.5em;
}
.timer .timer-actions button[data-action] {
font-family: monospace;
width: 6em;
border: thin solid #444;
background: #222;
color: #EEE;
padding: 0.5em;
cursor: pointer;
text-transform: uppercase;
}
.timer .timer-actions button[data-action]:hover {
background: #444;
border: thin solid #666;
color: #FFF;
}
<div class="timer">
<div class="timer-display"></div>
<div class="timer-actions">
<button data-action="toggle" data-state="initial">Start</button>
<button data-action="stop">Stop</button>
</div>
</div>
Note: This solution is not suitable if you like your interval works on the background, for example, playing audio or something else. But if you are confused for example about your animation not working properly when coming back to your page or tab, this is a good solution.
There are many ways to achieve this goal, maybe the "WebWorkers" is the most standard one but certainly, it's not the easiest and handy one, especially If you don't have enough Time, so you can try this way:
The basic concept:
build a name for your interval(or animation) and set your interval(animation), so it would run when user first time open your page : var interval_id = setInterval(your_func, 3000);
by $(window).focus(function() {}); and $(window).blur(function() {}); you can clearInterval(interval_id) everytime browser(tab) is deactived and ReRun your interval(animation) everytime browser(tab) would acive again by interval_id = setInterval();
Sample code:
var interval_id = setInterval(your_func, 3000);
$(window).focus(function() {
interval_id = setInterval(your_func, 3000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
Here's my rough solution
(function(){
var index = 1;
var intervals = {},
timeouts = {};
function postMessageHandler(e) {
window.postMessage('', "*");
var now = new Date().getTime();
sysFunc._each.call(timeouts, function(ind, obj) {
var targetTime = obj[1];
if (now >= targetTime) {
obj[0]();
delete timeouts[ind];
}
});
sysFunc._each.call(intervals, function(ind, obj) {
var startTime = obj[1];
var func = obj[0];
var ms = obj[2];
if (now >= startTime + ms) {
func();
obj[1] = new Date().getTime();
}
});
}
window.addEventListener("message", postMessageHandler, true);
window.postMessage('', "*");
function _setTimeout(func, ms) {
timeouts[index] = [func, new Date().getTime() + ms];
return index++;
}
function _setInterval(func, ms) {
intervals[index] = [func, new Date().getTime(), ms];
return index++;
}
function _clearInterval(ind) {
if (intervals[ind]) {
delete intervals[ind]
}
}
function _clearTimeout(ind) {
if (timeouts[ind]) {
delete timeouts[ind]
}
}
var intervalIndex = _setInterval(function() {
console.log('every 100ms');
}, 100);
_setTimeout(function() {
console.log('run after 200ms');
}, 200);
_setTimeout(function() {
console.log('closing the one that\'s 100ms');
_clearInterval(intervalIndex)
}, 2000);
window._setTimeout = _setTimeout;
window._setInterval = _setInterval;
window._clearTimeout = _clearTimeout;
window._clearInterval = _clearInterval;
})();
I was able to call my callback function at minimum of 250ms using audio tag and handling its ontimeupdate event. Its called 3-4 times in a second. Its better than one second lagging setTimeout
There is a workaround for this problem, although actually the tab must be made active in some window.
Make your inactive tab a separate browser window.
Don't make any other window maximized (unless the maximized window is behind yours).
This should give the browser the impression of always being active.
This is bit cumbersome, but also a quick win. Provided one has control over windows arrangement.

Using jQuery to countdown from 90 seconds beginning on the click of an element

Hi I was wondering if anyone can help me. I am trying to create a simple card game using html css and javascript. It has a 90 second timer which I want to start counting down on the first click of the card.
Any ideas how to do this?
Thank you!!
If you want to run a function after 90 seconds then
element.onclick = function () {
setTimeout(myFunctionAfter90Secs, 90 * 1000);
};
And you would define element to be the element that's clicked on (use a querySelector) and define your myFunctionAfter90Secs
If you want to display a timer then:
Html:
<div id="timer"></div>
<div id="card"></div>
<script>
var timer = document.querySelector("#timer");
var card = document.querySelector("#card");
var initialSeconds = 90;
card.onclick = function () {
var myInterval = setInterval(function() {
if (initialSeconds > -1) {
timer.innerHTML = initialSeconds;
initialSeconds--;
}
else {
clearInterval(myInterval);
}
}, 1 * 1000);
};
</script>
This will make sure your timer updates every second until it hits 0, then the reset should clear your interval but feel free to tweak the code to fix it

How to redirect a page at a specific time

I am trying to find a way to redirect a page to another page at exactly 7:58 EST Every day then redirect back at 9 PM EST every day any ideas or advice on this?
I created something for you to trigger your function every x seconds and redirect to wherever you want
window.setInterval(function(){ //This will trigger every X miliseconds
var date = new Date(); //Creates a date that is set to the actual date and time
var hours = date.getHours(); //Get that date hours (from 0 to 23)
var minutes = date.getMinutes(); //Get that date minutes (from 0 to 59)
if (hours == 7 && minutes == 58 ){
//redirect to where you want
} else if( hour = 21 && minutes == 00){
//redirect to where you want
}
}, 1000); //In that case 1000 miliseconds equals to 1 second
Now, talking about UTC and setting it. You can set it when you create your date, there is a topic talking only about that: Create a Date with a set timezone without using a string representation AND How to initialize a JavaScript Date to a particular time zone
Sometimes I would recomend using something like moment.js.
I hope my answer helps you someway
Redirecting to another page is quite straight forward, however redirecting back to the originating page isn't as easy.
To achieve this effect, you might consider wrapping the pages you want to navigate to and from, in an <iframe> element, where the page containing the <iframe> controls the navigation at those key times.
You could also consider setting up up an interval to check for and run this navigation logic (if needed) every one minute using setInterval(). To simplify the manipulation and querying of times (in relation to your timezone), you might find momentjs helpful.
These ideas are combined in the snippet below:
/*
Run this logic once per minute
*/
const oncePerMinute = () => {
/*
Get iframe and current iframe src
*/
const iframe = document.querySelector('iframe');
const iframeSrc = iframe.getAttribute('src');
/*
The url's to display for either time slot
*/
const dayUrl = 'daytimeurl'
const nightUrl = 'nighttimeurl'
/*
Adjust time to EST (-5hr)
*/
const momentEST = moment().utc().utcOffset('-0500');
/*
If between 7:58am and 9:00pm update iframe to show day url
*/
if(momentEST.isBetween(moment('7:58am', 'h:mma'), moment('9:00pm', 'h:mma'))) {
if(iframeSrc !== dayUrl) {
iframe.setAttribute('src', dayUrl);
}
}
/*
Othwise, update iframe to show night url
*/
else {
if(iframeSrc !== nightUrl) {
iframe.setAttribute('src', nightUrl);
}
}
}
/*
Will set interval to run oncePerMinute every minute
*/
setInterval(oncePerMinute, 1000 * 60);
oncePerMinute();
iframe {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<iframe></iframe>

How to create a simple countdown timer in JS?

I have very little experience in coding in general, however, I still need a timer that comes on a pop-up that goes from 20 or 30 minutes to 0, and it should display the time remaining (like MM:SS). Then, when the timer hits 0, a new pop-up should appear that displays some plain text. Is this even possible?
This could do the work
let time = 5;
let element = document.getElementById('countdown');
function lower() {
if(time >= 0) {
element.innerHTML = time--;
}
else {
console.log('popup')
//open popup here
}
}
setInterval(lower, 1000);
I did not do the time format tho. Only shows in seconds now

Initializing a repetitive action with Javascript with getTime()

I'm a newb to development, so this may come off as a stupid question, but I figured I'd ask anyway. After all, me looking bad just makes you look better. :)
I want to change the css style on an element based on time. I've tried a few different methods and can get the time to display inside of html, but I can't use the time to trigger other events. I've put this little page together to make things simpler for me.
<html>
<head>
<title>timerTest</title>
<style type="text/css">
#box {
height:200px;
width: 200px;
background-color: red;
}
</style>
</head>
<body onload="maFucktion()">
<div id="box">T</div>
<script type="text/javascript">
var box = document.getElementById('box');
function maFucktion()
{
var d = new Date();
for(i=0; i > 100; ++i)
{
if((d.getTime() % 1000) < 499)
{
box.style.backgroundColor = "blue";
box.innerHTML = d.getTime() % 1000;
}
else
{
box.style.backgroundColor = "red";
box.innerHTML = d.getTime() % 1000;
}
}
}
</script>
</body>
</html>
So, what my little brain tells me this should do is, on page load, execute maFucktion() which should initiate a for loop which:
(1)sets a new Date()
(2)gets the time since january 1 1970 in milliseconds with the getTime() method
(3)breaks it down to the half second with the modulus operator
(4)and delivers a new background color and the division remainder of the condition based on whether the value is between 0-499 or else
I want it to change box.style.backgroundColor every half second which should end up looking like one of those silly banner ads from 1998, but I can't get it to automatically change.
I know a for loop probably isn't the best, but it should at least display a new innerHTML value for #box, right?
You need to use setTimeout() or setInterval() to trigger an action at some time in the future. See here and here for doc.
Looping and checking the time is very, very bad in javascript because it locks up the browser from processing user events.
So to change the background color every half second, you could do this:
var isBlue = false;
var box = document.getElementById('box');
setInterval(function() {
box.style.backgroundColor = isBlue ? "red" : "blue";
isBlue = !isBlue;
}, 500);
You can see a working demo here: http://jsfiddle.net/jfriend00/n5Mhz/.
What you really want to do here is use a timer. Have the timer call the function every 1/2 second:
<script type="text/javascript">
var box = document.getElementById('box');
var clrs = "#ff0000,#0000ff".split(",")
var cPos = 0;
function flipC() {
box.style.backgroundColor = clrs[cPos];
cPos = 1-cPos;
window.setTimeout(flipC,500)
}
flipC()
</script>

Categories

Resources