setInterval: changing numbers in function depending on times that event has occured - javascript

I need to figure out how to use setInterval() to make text increase 1px(font-size) every 1000 ms. Here's my setup:
function boom() {
var fwuff = document.getElementById("fwuff");
fwuff.style.display="block";
fwuff.style.textAlign="center"
setInterval(function(){
fwuff.style.fontSize=??
}, 1000);
}
What I don't know is what to put in the fwuff.style.fontSize so I can get the size to increase every time the event occurs. Does anyone understand and know how to do this?

Just use a variable :
function boom() {
var fwuff = document.getElementById("fwuff");
var myAwesomeVar = 10; //Base font size
fwuff.style.display="block";
fwuff.style.textAlign="center"
setInterval(function(){
fwuff.style.fontSize= myAwesomeVar + "px";
myAwesomeVar++;
}, 1000);
}

You can use a global variable or get the current fontSize in order to change it. Using a global variable will be slightly more efficient, however if you do not know the size of the font you are changing, you can use the fontSize of the element.
Fiddle
Getting then setting the fontSize:
function boom() {
var fwuff = document.getElementById("fwuff");
var myAwesomeVar = 10; //Base font size
fwuff.style.display="block";
fwuff.style.textAlign="center";
setInterval(function(){
curFontSize = $('#fwuff').css('fontSize');
FontSizeNumber = parseInt(curFontSize);
newFontSizeNumber = FontSizeNumber + 1 + 'px';
$('#fwuff').css('fontSize', newFontSizeNumber);
}, 1000);
}
or alternatively, you could use a variable:
function boom() {
var fwuff = document.getElementById("fwuff");
var myAwesomeVar = 10; //Base font size
fwuff.style.display="block";
fwuff.style.textAlign="center";
fontSizeVar = 12;
setInterval(function(){
fontSizeVar++;
newFontSizeVal = fontSizeVar + 'px';
$('#fwuff').css('fontSize', newFontSizeVal);
}, 1000);
}
Note: the question was tagged jquery. If this was accidental and you want me to convert to traditional JS, just ask.

Related

Image animation with speed control

We have some problem with our image animation with speed control.
It make use of a timeout to change the image, but we want to change the timeout value with a slider, but for some sort of reason, it doesn't work. Can someone help us out ?
We have a Jfiddle here: http://jsfiddle.net/Kbroeren/fmd4xbew/
Thanks! Kevin
var jArray = ["http://www.parijsalacarte.nl/images/mickey-mouse.jpg", "http://www.startpagina.nl/athene/dochters/cliparts-disney/images/donad%20duck-106.jpg", "http://images2.proud2bme.nl/hsfile_203909.jpg"];
var image_count = 0;
function rollover(image_id, millisecs) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
rollover("img1", 200);
$(function () {
var value;
var $document = $(document),
$inputRange = $('input[type="range"]');
// Example functionality to demonstrate a value feedback
function valueOutput(element) {
var value = element.value,
output = element.parentNode.getElementsByTagName('output')[0];
output.innerHTML = value;
}
for (var i = $inputRange.length - 1; i >= 0; i--) {
valueOutput($inputRange[i]);
};
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
rollover("img1", 200);
});
// end
$inputRange.rangeslider({
polyfill: false
});
});
You keep creating more and more infinite function calls without stopping them.
After you call your function the first time, it keeps calling itself.
then you call it again with different interval (millisecs) and it will also start call itself....
You can try two different approach.
1.Use setInterval instead of setTimeout. Use clearInterval to clear the interval before setting it with a new value.
/// Call animation() every 200 ms
var timer = setInterval("Animation()",200);
function ChageSpeed(miliseces){
///Stop calling Animation()
clearInterval(timer);
/// Start calling Animation() every "miliseces" ms
timer = setInterval("Animation()",miliseces);
}
function Animation(){
/// Animation code goes here
}
2.Or, Instead, Set your interval as a global variable (not cool) and just change it value when the user want to change the animation speed.
var millisecs = 200;
function rollover(image_id) {
var image = document.getElementById(image_id);
image.src = jArray[image_count];
image_count++;
if (image_count >= jArray.length) {
image_count = 0;
}
var timeout = setTimeout("rollover('" + image_id + "'," + millisecs + ");", millisecs);
}
$document.on('change', 'input[type="range"]', function (e) {
valueOutput(e.target);
millisecs = YourNewValue;
});

Javascript gradual width increase

I'm trying to gradually increase the elements of 2 id's in javascript using a Timeout. I can get one working but when trying to call another element into the same function it only does one iteration then crashes after the first recursive call.
I'm passing two id's for the elements. and I want the left element to gradually increase while the right element gradually increases in width.
Heres what ive got
function grow(elementL, elementR)
{
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL = htL + 5;
var movementR = htR - 5;
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
if (movementL > 1000) {
clearTimeout(loopTimer);
return false;
}
var loopTimer = setTimeout('grow(\''+elementL+','+elementR+'\')',50);
}
You could simplify this (removing the script-generation) by using setInterval -- this repeats the function call until you cancel it.
function grow(elementL, elementR)
{
var loopTimer = setInterval(function() {
if (!growStep(elementL, elementR)) {
clearInterval(loopTimer);
}
}, 50);
}
function growStep(elementL, elementR) {
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL = htL + 5;
var movementR = htR - 5;
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
if (movementL > 1000) {
return false;
}
return true;
}
(Fiddle)
Edit
Yeah, I guess the only problem with the OP code is that it passes a string to setTimeout, rather than the function itself:
var loopTimer = setTimeout(function() {
grow(elementL, elementR);
},50);
setTimeout('grow(\''+elementL+','+elementR+'\')',50)
would need to be
setTimeout('grow(\''+elementL+'\',\''+elementR+'\')',50)
// ^^ ^^
to work. But don't do that. Pass a function expression to setTimeout:
setTimeout(function() {
grow(elementL, elementR);
}, 50)

Setting a time for flicker animation on img

I'm using this code to make my logo flicker on my website. But It becomes annoying when it continues to flicker while browsing, how can I set a time to allow it to flicker for something like the first 15seconds on page load, then stops?
JS code I'm using:
$(document).ready(
function(){
var t;
const fparam = 100;
const uparam = 100;
window.flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = setTimeout('window.unflickr()',uparam);
}
else
t = setTimeout('window.flickr()',fparam);
}
window.unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = setTimeout('window.flickr()',fparam);
}
else
t = setTimeout('window.unflickr()',uparam);
}
t = setTimeout('window.flickr()',fparam);
});
You could have a counter, which you then use to decide whether you want to set another timeout. As a side note, you should never add functions to window and then passing a string to setTimeout. Always just pass the function itself:
$(document).ready(function(){
var t;
var amount = 0;
const fparam = 100;
const uparam = 100;
function timeout(f, t) { // this function delegates setTimeout
if(amount++ < 150) { // and checks the amount already (un)flickered
setTimeout(f, t); // (150 * 100 ms = 15 s)
}
}
var flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = timeout(unflickr,uparam);
}
else
t = timeout(flickr,fparam);
};
var unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = timeout(flickr,fparam);
}
else
t = timeout(unflickr,uparam);
};
t = timeout(flickr,fparam);
});
I see you're using jquery, you could use the following, if I remember correctly, all the stuff I use below has been in jquery since 1.0, so you should be good:
counter = 1;
function hideOrShow(){
$(".classToSelect").animate({"opacity": "toggle"}, 100);
counter = counter +1;
if (counter >= 21) clearInterval(flickerInterval);
}
flickerInterval = setInterval(hideOrShow, 100);
Change the selector, animation duration, and variable names to whatever you fancy/need.

increment progressbar every x seconds

I basically need a jQuery UI progress bar to increment x amount every x seconds. After it reaches 100% it needs to run a function to get some content.
Basically a timer.
EDIT: I don't need code to fetch content. I already have that.
var progressBar = $('#progress-bar'),
width = 0;
progressBar.width(width);
var interval = setInterval(function() {
width += 10;
progressBar.css('width', width + '%');
if (width >= 100) {
clearInterval(interval);
}
}, 1000);
jsFiddle.
Assuming that you're using the jQueryUI progressbar:
var tick_interval = 1;
var tick_increment = 10;
var tick_function = function() {
var value = $("#progressbar").progressbar("option", "value");
value += tick_increment;
$("#progressbar").progressbar("option", "value", value);
if (value < 100) {
window.setTimeout(tick_function, tick_interval * 1000);
} else {
alert("Done");
}
};
window.setTimeout(tick_function, tick_interval * 1000);
Demo here
jQuery UI has a progress bar widget. You can set its value inside setInterval. Run clearInterval when complete event is raised.

Rotate Background Image of Body by Time

Can someone help me make a simple javascript to get element body so I can alternate its style to change background images every X seconds?
There are three things you'll need (two of which have been mentioned by other answers):
The builtin function setInterval(), to fire off a handler function every X seconds.
The expression document.body, which gets you a direct reference to the DOM object for the body element.
A function (to be passed to setInterval()) which will switch between images. This will probably require some data structure to remember the list of images to switch between.
For example:
var images = ['./image1.jpg', './image2.jpg'];
var curImage = 0;
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(' + images[curImage] + ')'
}
window.setInterval(switchImage, numSeconds * 1000);
Set a function to switch backgrounds and add an interval to do it.
Backgrounds are contained in array bgArr.
bgArr = ['images/bg1.jpg', 'anotherdir/bg2.jpg', 'otherone/bg3.jpg'];
bgCur = 0;
backgroundSwitch = function()
{
if (bgCur == bgArr.length) bgCur = 0;
document.body.style.backgroundImage = 'url('+ bgArr[bgCur++]+ ')';
}
window.setInterval(backgroundSwitch, 30000); // Switch every 30 seconds.
check out setInterval
setInterval(function () {
document.body.style.backgroundImage = new_image;
}, 3000);

Categories

Resources