display diffrent images depending on time - javascript

So I have a sort of homepage with some code to change the background based on the time. My problem is: it only checks the time when the page first loads, I need it to be constantly checking for it. Here is my code, please help.
var today2 = new Date();
var h2 = today2.getHours();
if (h2 > 18) {
document.body.style.backgroundImage = "url('cityatnight2.jpg')";
}
else if (h2 < 9) {
document.body.style.backgroundImage = "url('sunrise2.jpg')";
}
else {
document.body.style.backgroundImage = "url('homescreen3.jpg')";
}

I would suggest using the setInterval command. It allows you to specify that code run at a given interval. For example, to run every hour, you could do this:
function SetBackground()
{
var today2 = new Date();
var h2 = today2.getHours();
if (h2 > 18) {
document.body.style.backgroundImage = "url('cityatnight2.jpg')";
}
else if (h2 < 9) {
document.body.style.backgroundImage = "url('sunrise2.jpg')";
}
else {
document.body.style.backgroundImage = "url('homescreen3.jpg')";
}
}
// 1 Hour Interval
window.setInterval(SetBackground, 60 * 60 * 1000);
Read more about that function here: https://www.w3schools.com/jsref/met_win_setinterval.asp

Try this code.
var changeBg = function(num){
if (num > 18) {
document.body.style.backgroundColor = "red";
}
else if (num < 9) {
document.body.style.backgroundColor = "blue";
}
else {
document.body.style.backgroundColor = "black";
}
}
setInterval(function(){
var today2 = new Date();
var h2 = today2.getSeconds(); //edit here. sec -> hour.
console.log(h2)
changeBg(h2);
},1000) //and edit here. 1000 means 1sec

Related

Timer doesn't start running

I tried to make a normal Timer in Javascript and started coding something with help of some Tutorials.
I did it the same way as in the tutorial but my timer actually doesn't start running, and i don't know why.
Here is my Code:
var time = 0;
var running = 0;
function startPause() {
if(running == 0){
running = 1;
increment();
}
else{
running = 0;
}
}
function reset(){
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
function increment() {
if(running == 1){
setTimeout(function(){
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}, 100);
}
}
</script>
i also made a fiddle you can check out here: https://jsfiddle.net/adamswebspace/5p1qgsz9/
what is wrong with my code?
I cleared a bit your code, and used setInterval instead of setTimeOut;
note that you have to use clearInterval in order to stop the timer
var time = 0;
var running = 0;
var timer = null;
function increment() {
time++;
var mins = Math.floor(time / 10 / 60);
var secs = Math.floor(time / 10);
var tenths = time % 10;
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + tenths;
}
function startPause() {
if (running === 0) {
running = 1;
timer = setInterval(increment, 1000);
} else {
running = 0;
clearInterval(timer);
}
}
function reset() {
running = 0;
time = 0;
document.getElementById("startPause").innerHTML = "Start";
}
you have to bind the function like the following
var vm = this;
vm.startPause = function startPause() {
if (running == 0) {
running = 1;
vm.increment();
} else {
running = 0;
}
}
https://jsfiddle.net/f7hmbox7/
In order for onclick to find the function in your code. It must be supplied in a <script> tag for JSFiddle.
You can just add
<script>
/** JS Here */
</script>
and it will work.
Keep in mind that all the errors coming from JS are showed in the console of your browser inspector.
https://jsfiddle.net/dzskncpw/

Javascript countdown timer to change image and link

Apologies in advance for being somewhat out of my depth here.
I am trying to use a JavaScript countdown timer on an ASP page to do the following - every sixty seconds after the a page loads, an image-based link will switch between one of five image/link combinations.
I've done something somewhat wrong here, and I can't find the problem. It never runs.
Thanks in advance for any assistance.
The images are named the following:
1_AdvoImg.gif 2_AdvoImg.gif 3_AdvoImg.gif 4_AdvoImg.gif 5_AdvoImg.gif
The urls are the following:
linkone.html linktwo.html linkthree.html linkfour.html linkfive.html
The html encapsulating the link is this:
<a id='AdvoLink' href='../'><img id='AdvoImg' src='' border="0"></a>
The javascript is this:
<script language="javascript">
function startTimer(duration) {
var timer = duration, seconds, imgprefix, imgname, linkurl;
imgprefix = 1;
setInterval(function () {
seconds = parseInt(timer % 60, 10);
imgname = imgprefix.concat("_AdvoImg.gif");
if (imgprefix == 1) {
linkurl = "linkone.html";
}
if (imgprefix == 2) {
linkurl = "linktwo.html";
}
if (imgprefix == 3) {
linkurl = "linkthree.html";
}
if (imgprefix == 4) {
linkurl = "linkfour.html";
}
if (imgprefix == 5) {
linkurl = "linkfive.html";
}
if (--timer <= 0) {
document.getElementById("AdvoLink").href = "";
document.getElementById("AdvoImg").src = imgname;
++imgprefix;
timer = duration;
}
}, 5);
}
window.onload = function () {
startTimer(60);
};
</script>
You are trying to build a timer inside a timer there.
Try keeping it as simple as possible.
What you actually need is just:
window.onload = function () {
setInterval(function () {
//your url changing magic here - without the timer stuff
}, 60000);
};
With this, your magic code should trigger every 60000 milliseconds => 60s => 1minute.
You could actually kinda "debug" it by using console.log() inside your loop.
dunno what you were using var seconds for so I removed it
edited to stop image number going over 5, change if loop to whatever number you need
function startTimer(duration) {
var timer = duration;var seconds;var imgprefix;var imgname;var linkurl;
imgprefix = 1;
setInterval(function() {
imgname = imgprefix+"_AdvoImg.gif";
if (imgprefix == 1) {
linkurl = "linkone.html";
}
if (imgprefix == 2) {
linkurl = "linktwo.html";
}
if (imgprefix == 3) {
linkurl = "linkthree.html";
}
if (imgprefix == 4) {
linkurl = "linkfour.html";
}
if (imgprefix == 5) {
linkurl = "linkfive.html";
}
document.getElementById("timer").innerHTML=timer;
timer--;
if (timer <= 0) {
document.getElementById("AdvoLink").href = linkurl;
document.getElementById("AdvoImg").src = imgname;
document.getElementById("result").innerHTML = "image src = "+imgname+" and href = "+linkurl;
if(imgprefix < 5){++imgprefix;}else{imgprefix =1;}
timer = duration;
}
}, 200//speed up and slow down here, in milliseconds
);
}
window.onload = function () {
startTimer(10);
};
<a id='AdvoLink' href='../'><img id='AdvoImg' src='' border="0"></a>
<div id="timer"> </div>
<div id='result'> </div>

Javascript concat() not working as it should be

<!DOCTYPE html>
<html>
<script>
function myFunction() {
var objDate = new Date();
var hours = objDate.getHours();
var mins = objDate.getMinutes();
var time = hours.concat(mins);
window.alert(time);
if (time>=1600&&time<=0900) {
document.body.style.background ="url('closed.png') no-repeat";
} else if (time>=1230&&time<=1315) {
document.body.style.background ="url('lunch.png') no-repeat";
} else {
document.body.style.background ="url('open.png') no-repeat";
}
}
setInterval(myFunction, 3000);
</script>
</html>
At line 8
"var time = hours.concat(mins);"
I get "Uncaught TypeError: undefined is not a function" and it refuses to continue. All I want to do is specify if its between a certain time then we are open, closed or at lunch. Schedule never really changes so it doesn't need to be more advanced than that.
concat() is for joining two arrays. You just want to join two strings. Try
var time = hours.toString() + mins.toString();
getHours() returns a number so it doesn't have a concat method, so your script should throw an error saying Uncaught TypeError: undefined is not a function
function myFunction() {
var objDate = new Date();
var hours = objDate.getHours()+'';
var mins = objDate.getMinutes();
var time = hours.concat(mins); //or hours + ':' + mins
window.alert(time);
}
setInterval(myFunction, 3000);
But for your calculation related to background style, it will be better to use time in minutes
function myFunction() {
var objDate = new Date();
var hours = objDate.getHours();
var mins = objDate.getMinutes();
var time = hours * 60 + mins;
if (time >= 960 || time <= 540) {
document.body.style.background = "url('closed.png') no-repeat";
} else if (time >= 750 && time <= 795) {
document.body.style.background = "url('lunch.png') no-repeat";
} else {
document.body.style.background = "url('open.png') no-repeat";
}
}
setInterval(myFunction, 3000);

How to change the speed of setInterval in real time

I would like to know how to change the speed of setInterval in real time e.g:
if (score < 10)
repeater = setInterval(function() {
spawnEnemy();
}, 1000);
if (score => 10)
repeater = setInterval(function() {
spawnEnemy();
}, 500);
I know this method doesn't work, but is there a way that I can achieve this some other way?
jsFiddle Demo
There is no way to change the interval speed itself once running. The only way to do it is to have a variable for the speed, and then clear the interval and start a new one with the new speed.
var speed = 500;
var changeSpeed = speed;
repeater = setInterval(repeaterFn, speed);
function repeaterFn(){
spawnEnemy();
if( changeSpeed != speed ){
clearInterval(repeater);
speed = changeSpeed;
repeater = setInterval(repeaterFn, speed);
}
}
function changeRepeater(){
changeSpeed = 700;
}
Another way would be to just use setTimeout rather than setInterval. Do the check every time so you can keep your speed logic in a seperate function.
var game_over = false;
var score = 0;
function getSpeedFromScore(score)
{
if (score > 20) {
game_over = true;
}
if (score < 10) {
return 1000;
} else {
return 500;
}
}
function spawnEnemyThenWait() {
if (!game_over) {
spawnEnemy();
var speed = getSpeedFromScore(score);
setTimeout(spawnEnemyThenWait, speed);
}
}
JS Fiddle http://jsfiddle.net/bq926xz6/
You can use clearInterval:
if (score < 10) {
clearInterval(repeater);
repeater = setInterval(spawnEnemy, 1000);
}
if (score => 10) {
clearInterval(repeater);
repeater = setInterval(spawnEnemy, 500);
}
But it depends on the context. If this snippet is executed more often, than it has to be, you will need some kind of mechanism to prevent it from resetting your interval all the time.
But there is (as I wrote in the comment to the question) no way to use clearInterval and change the interval itself. At least not without replacing it by a new interval as shown above.
You can use a game loop and track the spawn state in an enemy class:
// press f12 so see console
function Enemy() {
this.spawned = false;
this.spawnOn = 20;
this.tick = function () {
this.spawnOn = this.spawnOn - 1;
if (this.spawnOn == 0) {
this.spawned = true;
}
}
this.goBackToYourCage = function () {
this.spawnOn = Math.floor(Math.random() * 50) + 1;
this.spawned = false;
}
}
var enemy = new Enemy();
window.setInterval(function () {
enemy.tick();
if (enemy.spawned) {
console.log('spawned');
enemy.goBackToYourCage();
console.log('Next spawin in :' + enemy.spawnOn);
}
}, 100);
http://jsfiddle.net/martijn/qxt2fe8y/2/

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories