Initializing a repetitive action with Javascript with getTime() - javascript

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>

Related

if/else and setInterval

<script>
//when user clicks start button this function ensures all fields //are set to 0 and it
//sets the timer for the game (90seconds) and the second timer to //call showWord() every four seconds to display a new word
function startGame() {
numBadWordsField.innerHTML = '';
numGoodWordsField.innerHTML = '';
numWordsRight = 0;
numWordsWrong = 0;
correctWords = [];
showWord();
gameTimer = setInterval(gameTime, 1000);
timedWordDisplay = setInterval(showWord, 4000);
}
//this function is set to repeat every four seconds unless the user //types the word
//correctly in which case code in the checkWord() function resets setInterval then and a new word appears
function showWord() {
let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
currentWord = wordsLevelOne[randomNum];
//i put all correctly typed words in an array to avoid them being repeated
//if the random word has been typed correctly and is in the array then i tell the
//program to repeat the function until a new word is found.
if (correctWords.includes(currentWord)) {
showWord();
} else {
wordDisplayBox.innerHTML = currentWord;
setInterval(changeBar, 500);
answerBox.focus();
}
}
//this function is called oninput as user types in the word. it works perfectly (i think it does anyways)
//however i cannot figure out how to give instructions in the event the user does not type the
//word correctly before the four seconds are up and the setInterval repeats. I would like to
//in that case increment the words wrong score and reset the fields to be ready for the next
//word to be displayed
function checkWord() {
let currentWordLen = answerBox.value.length;
if (wordDisplayBox.innerHTML === answerBox.value) {
clearInterval(timedWordDisplay);
numWordsRight++;
correctWords.push(currentWord);
numGoodWordsField.innerHTML = numWordsRight;
answerBox.value = '';
answerBox.focus();
wordDisplayBox.innerHTML = '';
showWord();
timedWordDisplay = setInterval(showWord, 4000);
} else if (answerBox.value === currentWord.substring(0, currentWordLen)) {
answerBox.style.borderColor = 'green';
} else {
answerBox.style.borderColor = 'red';
}
}
//different topic than above but i also researched how to make my progress bar fill slowly over the course
//of the four seconds. i have written the following function identically to that on
//w3schools and other code yet it does not work.
//Any ideas?
function changeBar() {
let proBar = document.querySelector('#progressBar');
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
proBar.style.width = width + '%';
}
}
}
</script>
This project Im working on is a beginner level speed typing game that displays a different word for the user to type in less than four seconds.I have a setInterval that displays a different word every four seconds unless the user types the word correctly at which point the timer starts over then. What I am stumped at is how can I make it so that if the correct answer is not typed in before the interval resets (at the end of four seconds) the program knows to increment the 'wrong answer' score and to reset the input boxes for the next word just like when it is typed correctly. i have attached the parts of my code i think may be relevant. If anyone has any suggestions let me know. I am eager to learn. **I am not familiar yet with JQuery. Please describe any suggestions using vanilla JS
This feature should be implemented in the showWord function.
showWord is executed after 4 seconds have passed, which is when the time is up. Executing this function means the user has failed to type the word in time.
I would do something like this :
function showWord() {
// At this point, the user has lost. We perform the according operations
numWordsWrong++;
answerBox.value = '';
// etc.
// What follows is the rest of the function you've already implemented
let randomNum = Math.floor(Math.random()*wordsLevelOne.length);
// etc.
}
To answer your question about the progress bar, you are setting an interval to run changeBar every 500 milliseconds, which would cause the progress bar to reset every half second. If you want a delay before starting the progress bar use setTimeout.
In addition, you are running your progress bar to move 1% every 10 milliseconds which would result in the bar completing in 1 second. If you want the bar to complete in 4 seconds, set the id interval to run every 40 milliseconds.
Without seeing your css and html, I have to assume you're using the correct id names in your code but if nothing is happening at all, that could also be the cause.
I have looked at the W3Shools code you reference and I tried to replicate what you were trying to do and got this to work:
<html>
<head>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
</head>
<body>
<div id="myProgress">
<div id="myBar"></div>
</div>
</body>
<script>
function changeBar() {
let proBar = document.querySelector('#myBar');
var width = 1;
var id = setInterval(frame, 40);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
proBar.style.width = width + '%';
}
}
}
setTimeout(changeBar, 100);
</script>
</html>
One solution can be to create a new function (ex : showWordBecauseTimeout) and call it in your setInterval instead of showWord. And call that function in showWord fct instead of in startGame fct.
So the new code would be something like :
function showWord() {
clearInterval(timedWordDisplay);
timedWordDisplay = setInterval(showWordBecauseTimeout, 4000);
// you also need to move the cleaning of the input in the showWord fct
// ...
}
function showWordBecauseTimeout() {
numWordsWrong++;
showWord()
}
Hope that it helps you :).

Rotating several images with different timings

I have three images side by side, left, middle and right. I want the first image on the left to change after 2 seconds, then the one in the middle to change 2 seconds later and then the one on the right to change 2 seconds after that. Then after another 2 seconds I want the first one on the left to change again and for the sequence to start all over again.
I've put together the javascript code for each image to have a certain start time and then a 6 second interval before changing again, this gives the effect I'm looking for.
The sequence works the first time round but when the first image is due to run through the sequence the second time round the whole thing seems to stick a bit and then all the images start changing together, as if they are all affecting one another. I don't know why this is since the code refers to each separately. Any help would be appreciated. Here's the code:
HTML Code:
<div>
<img id="mainImage" src="firstimage.jpg">
<img id="mainImage1" src="secondimage.jpg">
<img id="mainImage2" src="thirdimage.jpg">
</div>
Javascript Code:
<script>
var myImage = document.getElementById("mainImage");
var imageArray = ["image1.jpg","image2.jpg","image3.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setTimeout(changeImage, 0000);
setInterval(changeImage,6000);
</script>
<script>
var myImage1 = document.getElementById("mainImage1");
var imageArray1 = ["image4.jpg","image5.jpg","image6.jpg"];
var imageIndex1 = 0;
function changeImage1() {
myImage1.setAttribute("src",imageArray1[imageIndex1]);
imageIndex1++;
if (imageIndex1 >= imageArray1.length) {
imageIndex1 = 0;
}
}
setTimeout(changeImage1, 2000);
setInterval(changeImage1,6000);
</script>
<script>
var myImage2 = document.getElementById("mainImage2");
var imageArray2 = ["image7.jpg","image8.jpg","image9.jpg"];
var imageIndex2 = 0;
function changeImage2() {
myImage2.setAttribute("src",imageArray2[imageIndex2]);
imageIndex2++;
if (imageIndex2 >= imageArray2.length) {
imageIndex2 = 0;
}
}
setTimeout(changeImage2, 4000);
setInterval(changeImage2,6000);
</script>
Solution:
For each
setTimeout(changeImage2, x);
setInterval(changeImage2,6000);
change to
setTimeout(function() {
setInterval(changeImage2,6000);
}, x);
Check here: https://jsfiddle.net/bstd3fqu/4/
Explanation:
setTimeout() doesn't make runtime to sleep for certain time. It simply set a timer to execute the mentioned function after certain time. So all setInterval() calls are executing at almost same time in your implementation. I am just setting the interval in the setTimeout function so that these setInterval() calls are executing at different times.

Body Background based on hour of the day JS

<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.

show and hide with delays on a loop but no animation

I have a jsfiddle for this
Jsfiddle
The problem is, I am trying to create a script that ones a button is clicked flashes an image (car lights) on and off for a period of time. It works fine, but in IE8 since the lights are png the animation for it is causing a black background and border as it blinks on and off. So I trying to duplicate the same thing, but without using animation.
In my jsfiddle, the first function for the first click div represents what i am trying to do without animation, but it is not repeating. The code:
$('.oneD').click(function(){
for (var i = 0; i <= 9; i++) {
$('.oneP').show();
setTimeout(function(){
$('.oneP').hide();
}, 1000);
}
});
The 2nd function is the one I already created that does work, but it has the animation:
$('.twoD').click(function(){
for (var i = 0; i <= 9; i++) {
$(".twoP").fadeIn(1000, function () {
$(".twoP").hide();
});
}
});
Keep in mind that the jsfiddle is just a simple mock not using images. I am just looking for the functionality in which i can incorporate this. I appreciate your time in helping me with this.
instead of setTimeout() use setInterval() and clearInterval() like this:
$('.oneD').click(function(){
$('.oneP').show();
var interval = setInterval(function(){
$('.oneP').hide();
}, 1000);
//*after a number of time or loop
interval.clearInterval();
});
setInterval() "Loop" throught the function it is given every number of millisecond you pass it. and clearInterval() stop the "Loop".
I'd do it like this :
$('.oneD, .twoD').on('click', function(){
for (var i=0; i<9; i++)
$('.'+this.className.replace('D', 'P')).delay(1000).show(0)
.delay(1000).hide(0);
});
FIDDLE
This uses a selector for both elements and the same event handler, then swaps out the D for a P in the showing and hiding.
As for using delay() and making this work, hide() and show() will work just as the animated jQuery methods if a value for the duration is passed, even if that value is zero.
Fiddle here: http://jsfiddle.net/HxFpr/
var i;
$('.twoD').click(function(){
i = 0;
loopFlash();
});
function loopFlash(){
if(i < 10){ // flash 5 times (1 on 1 off = 2 cycles)
$('.twoP').toggle();
var flashing = setTimeout(loopFlash,500);
}
i++;
}
Yet another solution for you.
No Animation - with single interval
With animation - pure jQuery
http://jsfiddle.net/x6Kpv/6/
var noAnimationHandler = function() {
setInterval(function() {
var $el = $('.oneP');
$el[$el.is(":visible") ? "hide" : "show"]();
}, 800);
};
var animationHanddler = function() {
$('.twoP').fadeIn(300, function() {
$(this).delay(150).fadeOut(300, animationHanddler);
});
}
$('.oneD').click(noAnimationHandler);
$('.twoD').click(animationHanddler);
Thanks

How to make an icon flash/blink, which is present in a web page

I started working on advanced java few days before(too late to start on that, I know). I am stuck with a specific task of making an icon (which is present on the task bar) blink. This blinking should happen based on a specific condition, which means that it can be achieved using javascript.
I have been searching for a while now but is there a way to make an icon appear and disappear every 1 second or so to bring in the blinking effect ?
HTML
<img src='image/source' alt='blinking!' id='blinking_image' />
Javascript
var img = document.getElementById('blinking_image');
var interval = window.setInterval(function(){
if(img.style.visibility == 'hidden'){
img.style.visibility = 'visible';
}else{
img.style.visibility = 'hidden';
}
}, 1000); //the 1000 here is milliseconds and determines how often the interval should be run.
This creates an anonymous function inside the setInterval that runs every 1 second (1sec == 1000milisec). To see more about setInterval checkout the mdn here on it.
Each time it runs it checks to see if the img is hidden or visible if it's hidden then it shows it if it's visible then it hides it. It does this by checking the style.visiblity property. Which you can learn more about here on the mdn.
Small fix
instead
if(img.display == 'hidden')
use
if(img.style.visibility == 'hidden')
You might find opacity works better because the image is still there, which means it is still clickable if necessary. Also you can add a clear interval to stop the flashing.
var mycounter = 0
interval = window.setInterval(function () {
if (img.style.opacity == '0.1') {
img.style.opacity = '1';
mycounter = mycounter + 1
if (mycounter == 7) {
clearInterval(interval);
}
} else {
img.style.opacity = '0.1';
}
}, 500); //the 1000 here is milliseconds and determines how often the interval

Categories

Resources