Setting a time for flicker animation on img - javascript

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.

Related

How to compare executed function output correctly?

So what im trying to do in general is -> get a moment when user scrolls up really fast on mobile device -> some text executed in console (for example)
What I have is 2 simple functions:
//calculate scroll speed
var mobileScroll = (function(){
var last_position, new_position, timer, delta, delay = 50;
function clear() {
last_position = null;
delta = 0;
}
clear();
return function(){
new_position = window.scrollY;
if ( last_position !== null ){
delta = new_position - last_position;
}
last_position = new_position;
clearTimeout(timer);
timer = setTimeout(clear, delay);
return delta;
};
})();
Then I'm trying to compare the outputted value with some static number like this:
var scrolledFast = function scrolledFast(e) {
console.log("scroll: " + mobileScroll());//works fine
console.log(mobileScroll());//always 0
//if statement does not work
if(document.body.classList.contains('on-mobile-device') && mobileScroll() < -200 ){
console.log('Scrolled up fast enough');
}
}
document.addEventListener('scroll', scrolledFast);
The problem is that I don't understand why I can get the outputted value like this:
console.log("scroll speed: " + mobileScroll()); // I see "scroll: -100" or some other value
But when I'm trying to get something like:
console.log(mobileScroll());
//or
var mobScrollSpeed = mobileScroll();
console.log(mobScrollSpeed);
it is always 0...

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)

Simple animation change height without jquery

I need simple animation on simple js. I think jquery too much for that. I need to increase or decrease the height of the block by pressing the buttons, but this work only on Opera (.
Example
function global_animate(element, property_to_map, duration, callback) {
duration = duration || 1000;
var delta = function (a) { return a; };
var start = new Date().getTime();
var property_from_map = {};
var property_units_map = {};
for (var property in property_to_map) {
property_from_map[property] = window.getComputedStyle(element, null)[property] || element.currentStyle[property];
property_units_map[property] = parseUnits(property_from_map[property]);
property_from_map[property] = parseInt(property_from_map[property]);
property_to_map[property] = parseInt(property_to_map[property]);
}
function parseUnits(a) {
try {
return a.match(/^\d+(\w{2}|%);?$/i)[1];
} catch (e) {
return "";
}
}
setTimeout(function() {
var now = (new Date().getTime()) - start;
var progress = now / duration;
for (var property in property_to_map) {
var result = (property_to_map[property] - property_from_map[property]) * delta(progress) + property_from_map[property];
element.style[property] = result.toFixed(2) + property_units_map[property];
}
if (progress < 1)
setTimeout(arguments.callee, 10);
else
if (typeof callback == 'function')
callback();
}, 10);
}
you need to change the regexp from
alert("23.2px".match(/^\d+(\w{2}|%);?$/i));​ // alert null
to something like this
alert("23.2px".match(/^\d+\.*\d*(\w{2}|%);?$/i));​ // alert ["23.2px", "px"]
I think the problem lies in your regex: a.match(/^\d+(\w{2}|%);?$/i)[1];. The second time it runs it does’t catch the units properly.
If I hard code the units to 'px', it works for me (in chrome): http://jsfiddle.net/9DCA5/5/
Maybe you can debug from there?
Method getComputedStyle() is not supported in IE, which uses the "currentStyle" property instead.

How to set timer in mootools

I am trying to make a slide show in mootools, and was trying delay function to make a periodic effect in slideshow but it was not working. So i am planning to make a timer function, but have no idea how to do that.
here is something which i have done..i little messy i guess
function slideImages(id_new, id_old){
console.log($(id_new));
$(id_old).tween('opacity', [1,0]);
$(id_old).setStyle('display','none');
$(id_old).tween('margin-left', -980);
$(id_new).setStyle('display', 'block');
$(id_new).tween('opacity', [0,1]);
$(id_new).tween('margin-left', 180);
var c = id_new;
var d = id_old;
//timer = setInterval ( "timerFunction()", 5000 );
(slide(c, d)).delay(5000); //this isn't working and browser is getting hanged
}
function slide(c, d){
console.log(c);
if (c.split('_')[1].toInt() > 2){
id_new = 'image_'+ 0 ;
console.log(id_new);
}
else{
id_new = 'image_'+ (c.split('_')[1].toInt()+1);
console.log(id_new);
}
id_old = c;
slideImages(id_new, id_old);
};
there are many ways to use delay or setTimeout. here they are:
function slideImages(id_new, id_old) {
var c = $(id_new);
var d = $(id_old);
d.tween('opacity', [1, 0]);
d.setStyle('display', 'none');
d.tween('margin-left', -980);
c.setStyle('display', 'block');
c.tween('opacity', [0, 1]);
c.tween('margin-left', 180);
// your timer becomes global here, careful. crappy pattern.
// use a closure so it goes in the upper scope, allowing you to stop.
// cancel by clearTimeout(timer)
// pass function to delay, scope = null, arguments
timer = slide.delay(5000, null, [c, d]);
// or
timer = (function() {
slide(c, d);
}).delay(5000);
// or normal js
timer = setTimeout(function() {
slide(c, d);
}, 5000);
}
function slide(c, d) {
if (c.split('_')[1].toInt() > 2) {
id_new = 'image_' + 0;
console.log(id_new);
}
else {
id_new = 'image_' + (c.split('_')[1].toInt() + 1);
console.log(id_new);
}
id_old = c;
slideImages(id_new, id_old);
}
i've adapted this mootools diver scroller. at the moment you have to click the buttons to move left to right. I was wondering if any one could help me put a automated scroll in?
Check with this Link...
Also refer this code...
heres the js code
var totalImages = 3;
var currentImage = 1;
function workSlide(way) {
var currentAmount=$("holder2").getStyle("margin-left");
var myFx = new Fx.Tween('holder2',{duration: 600});
if(way == "right") {
if (currentImage <= totalImages-1) {
currentImage++;
var whichAmount = -(((currentImage-1)) * 920);
myFx.start('margin-left',currentAmount,whichAmount);
}
} else {
if (currentImage > 1) {
currentImage--;
var whichAmount = -(((currentImage-1)) * 920);
myFx.start('margin-left',currentAmount,whichAmount);
}
}
}

Categories

Resources