Javascript Slideshow Speed - javascript

I have this Code with a Slideshow for Images. I Would like to set the time the images are fixed. (Image one rest for 10min and then fade out). All the Images should rest about 10min. I like to use this for a Infoscreen in my company. Please help :)
(function() {
function Slideshow( element ) {
this.el = document.querySelector( element );
this.init();
}
Slideshow.prototype = {
init: function() {
this.wrapper = this.el.querySelector( ".slider-wrapper" );
this.slides = this.el.querySelectorAll( ".slide" );
this.previous = this.el.querySelector( ".slider-previous" );
this.next = this.el.querySelector( ".slider-next" );
this.index = 0;
this.total = this.slides.length;
this.timer = null;
this.action();
this.stopStart();
},
_slideTo: function( slide ) {
var currentSlide = this.slides[slide];
currentSlide.style.opacity = 1;
for( var i = 0; i < this.slides.length; i++ ) {
var slide = this.slides[i];
if( slide !== currentSlide ) {
slide.style.opacity = 0;
}
}
},
action: function() {
var self = this;
self.timer = setInterval(function() {
self.index++;
if( self.index == self.slides.length ) {
self.index = 0;
}
self._slideTo( self.index );
}, 3000);
},
stopStart: function() {
var self = this;
self.el.addEventListener( "mouseover", function() {
clearInterval( self.timer );
self.timer = null;
}, false);
self.el.addEventListener( "mouseout", function() {
self.action();
}, false);
}
};
document.addEventListener( "DOMContentLoaded", function() {
var slider = new Slideshow( "#main-slider" );
});
})();

Well, there is only on thing that controls anything timing related in your code, so its a pretty safe bet that's what you want to change.
You have a setInterval() in action with its time set to 3000. Change that to 600000 (10m * 60s * 1000ms) and you should be all set.

action: function() {
var self = this;
self.timer = setInterval(function() {
self.index++;
if( self.index == self.slides.length ) {
self.index = 0;
}
self._slideTo( self.index );
}, 1000*60*10);
This function uses setInterval, which expects interval in ms as the second parameter. In this example its set to 3000 which is 3 seconds.
Change it to what I wrote above (1000ms is 1 second * 60 = 1 minute * 10 = 10 minutes).

Related

Change function from button click to page load

Is it possible to transform this code to generate when the page loads instead of when the button is clicked. I tried to change the events to load but it does not function. I do not know what I exactly I am doing wrong.
<p><button id="generate">Generate</button></p>
<p><code id="output"></code></p>
(function() {
function IDGenerator() {
this.length = 8;
this.timestamp = +new Date;
var _getRandomInt = function( min, max ) {
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
}
this.generate = function() {
var ts = this.timestamp.toString();
var parts = ts.split( "" ).reverse();
var id = "";
for( var i = 0; i < this.length; ++i ) {
var index = _getRandomInt( 0, parts.length - 1 );
id += parts[index];
}
return id;
}
}
document.addEventListener( "DOMContentLoaded", function() {
var btn = document.querySelector( "#generate" ),
output = document.querySelector( "#output" );
btn.addEventListener( "click", function() {
var generator = new IDGenerator();
output.innerHTML = generator.generate();
}, false);
});
})();
There is small bug.
Just change the document object to window like below
window.addEventListener('DOMContentLoaded', function() {
});

First load a page with ajax then with increasing intervals

I am currently using this code on one of my sites,
I want the test.php to load immediately, however it waits till after the interval.
Then if continues every minute untill the page closes. This can cause very large bandwith useage.
$(document).ready(function () {
setInterval(function() {
$.get("test.php", function (result) {
$('#id').html(result);
});
}, 60000);
});
What I would like to achieve is.
Load the test.php on pageload.
Then load the page every 60 seconds
If the page has been open for 10 minutes double the intervals to 120sec.
20mins increase to 180 second intervals
30mins increase to 240 second intervals
And so on.
Thanks for any help
You could use setInterval to manage the increase in interval every 10 minutes, and use setTimeout to use that interval. To get the code executed immediately on page load, just rearrange the code a bit:
$(document).ready(function () {
var interval = 60000;
setInterval(function () {
interval += 60000;
}, 600000); // every 10 minutes
(function loop() {
$.get("test.php", function (result) {
$('#id').html(result);
});
setTimeout(loop, interval); // repeat after interval
})(); // execute immediately
});
Generic Approach
chainable factory function
Create custom timer functions "on the fly".
var timer1 = timerFactory( fnCallback, iRepeats, iDelay, iSteps );
While runtime one can set all parameters.
timer1
.setContext( { foo: true, bar: 'wow' } )
.setCallback( function() { alert(this.bar) } )
.setDelay( 10000 );
And destroy the timer when obsolete.
timer1.destroy()
var timerFactory = function( _fnCallback, _iRepeat, _iDelay, _iSteps, _oContext ) {
// sanitize arguments and set default values
if ( typeof _fnCallback != 'function' ) {
_fnCallback = function() {};
}
if ( typeof _iRepeat != 'number' || _iRepeat < 1 ) {
_iRepeat = 10;
}
if ( typeof _iDelay != 'number' || _iDelay < 0 ) {
_iDelay = 60000;
}
if ( typeof _iSteps != 'number' || _iSteps < 0 ) {
_iSteps = _iDelay;
}
if ( typeof _oContext != 'object' ) {
_oContext = this;
}
var i = _iRepeat,
_getInterval = function() {
if ( --i ) {
return _iDelay;
}
i = _iRepeat;
return _iDelay += _iSteps;
},
_handle = function() {
_fnCallback.call( _oContext );
_setTimeout = setTimeout(_handle, _getInterval())
};
_handle();
// public methods (chainable)
this.destroy = function() {
clearTimeout( _setTimeout );
_fnCallback = _iRepeat = _iDelay = _iSteps =
_oContext = i = _getInterval = _handle = undefined;
return this;
}
this.setCallback = function( fnCallback ) {
_fnCallback = fnCallback;
return this;
}
this.setRepeats = function( iRepeat ) {
_iRepeat = iRepeat;
return this;
}
this.setDelay = function( iDelay ) {
_iDelay = iDelay;
return this;
}
this.setSteps = function( iSteps ) {
_iSteps = iSteps;
return this;
}
this.setContext = function( oContext ) {
_oContext = oContext;
return this;
}
// deploy public methods
return this;
};
$(document).ready(function () {
/* actual question
timerFactory(
function(){ $.get("test.php", function (result) { $('#id').html(result); }) }
)
*/
// examples
timerFactory( function() {$('#_0').append('ajax default: 10, 6000, 6000<br>')} );
timerFactory( function() {$('#_1').append('1, 0, 250<br>')}, 1, 0, 250 );
timerFactory( function() {$('#_2').append('3, 1500<br>')}, 3, 1500 );
timerFactory( function() {$('#_3').append('1, 3000, ->destroy<br>')}, 1, 3000 ).destroy();
// example with context and alternative syntax
myClass = { // context example
methFOO : function() {$('#_4').append('ALT meth1<br>')},
methBAR : function() {$('#_4').append('ALT meth2<br>')}
}
timerFactory( myClass.methFOO, 1, 1, 1 )
.setCallback( function() {this.methBAR()} )
.setRepeats( 3 )
.setDelay( 1000 )
.setSteps( 500 )
.setContext( myClass );
});
html, body {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
div {
border: 1px solid #999;
box-sizing: border-box;
float: left;
height: 100%;
width: 20%;
}
<div id="_0"></div>
<div id="_1"></div>
<div id="_2"></div>
<div id="_3"></div>
<div id="_4"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Change images with different timeinterval using Js or jquery

How to change images with different time interval in a single div using CSS3, JavaScript or jQuery. At the last time interval should be cleared.
You can try this http://codepen.io/jammer99/pen/PNErKp
var timing = [1000, 2000, 500, 300, 800],
timeouts
function runinterval() {
timeouts = setTimeout(function() {
clearTimeout(timeouts);
timing.shift();
$(".imgholder").css("background-image", "url(https://unsplash.it/100/100/?random&i=" + new Date().getTime() + ")")
if (timing.length != 0)
runinterval();
}, timing[0])
}
runinterval();
Maybe something like this can help you.
var setTimer = (function(){
function setTimer( options ){
this.timings = options.timings;
this.element = options.element;
this.images = options.images;
this.index = -1;
this.interval = false;
this.init();
}
setTimer.prototype.init = function(){
this.image_ = document.createElement('img');
this.image_.setAttribute('class','slider-image');
this.element.appendChild( this.image_ );
this.set();
};
setTimer.prototype.set = function(){
if( this.interval && false !== this.interval ){
clearTimeout( this.interval );
}
if( this.index >= this.images.length-1 ){ this.index = 0; }
else{ this.index++; }
var timing = this.timings[this.index];
console.log(this.index);
console.log(timing);
this.interval = (function(_this){
return setTimeout(function(){
_this.switch_image();
},timing);
})(this);
};
setTimer.prototype.switch_image = function(){
var index = this.index;
console.log('switching image to '+this.images[index]);
this.image_.setAttribute('src',this.images[index]);
this.set();
}
return setTimer;
})();
setTimeout(function(){
var options = {
timings: [10,1000,2000],
images : [ 'url1','url2','url3'],
element: document.getElementById('your-image-container-id')
};
new setTimer(options);
},1000);

jQuery SVG animate : scroll and fadeIn

I'm trying to implement a codrops plugin I found and it's working quite well but I have trouble when it comes to improve it.
http://tympanus.net/codrops/2013/12/30/svg-drawing-animation/
My page is divided into three sections, when you click on one of the three sections on the menu, the content fades in.
http://alexandrebeaumont.com/so/layout.png
When you scroll down my animations load perfectly but I would like them to be reloaded each time you click on the menu because now, if I scroll in one section, the animations are launched in everyone of them...
EDIT I pasted the whole code since after reading again the script I'm not sure at all what could giver me my solution
(function() {
'use strict';
var docElem = window.document.documentElement;
window.requestAnimFrame = function(){
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback){
window.setTimeout(callback, 1000 / 60);
}
);
}();
window.cancelAnimFrame = function(){
return (
window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
window.oCancelAnimationFrame ||
window.msCancelAnimationFrame ||
function(id){
window.clearTimeout(id);
}
);
}();
function SVGEl( el ) {
this.el = el;
this.image = this.el.previousElementSibling;
this.current_frame = 0;
this.total_frames = 60;
this.path = new Array();
this.length = new Array();
this.handle = 0;
this.init();
}
SVGEl.prototype.init = function() {
var self = this;
[].slice.call( this.el.querySelectorAll( 'path' ) ).forEach( function( path, i ) {
self.path[i] = path;
var l = self.path[i].getTotalLength();
self.length[i] = l;
self.path[i].style.strokeDasharray = l + ' ' + l;
self.path[i].style.strokeDashoffset = l;
} );
};
SVGEl.prototype.render = function() {
if( this.rendered ) return;
this.rendered = true;
this.draw();
};
SVGEl.prototype.draw = function() {
var self = this,
progress = this.current_frame/this.total_frames;
if (progress > 1) {
window.cancelAnimFrame(this.handle);
this.showImage();
} else {
this.current_frame++;
for(var j=0, len = this.path.length; j<len;j++){
this.path[j].style.strokeDashoffset = Math.floor(this.length[j] * (1 - progress));
}
this.handle = window.requestAnimFrame(function() { self.draw(); });
}
};
SVGEl.prototype.showImage = function() {
classie.add( this.image, 'show' );
classie.add( this.el, 'hide' );
};
function getViewportH() {
var client = docElem['clientHeight'],
inner = window['innerHeight'];
if( client < inner )
return inner;
else
return client;
}
function scrollY() {
return window.pageYOffset || docElem.scrollTop;
}
// http://stackoverflow.com/a/5598797/989439
function getOffset( el ) {
var offsetTop = 0, offsetLeft = 0;
do {
if ( !isNaN( el.offsetTop ) ) {
offsetTop += el.offsetTop;
}
if ( !isNaN( el.offsetLeft ) ) {
offsetLeft += el.offsetLeft;
}
} while( el = el.offsetParent )
return {
top : offsetTop,
left : offsetLeft
};
}
function inViewport( el, h ) {
var elH = el.offsetHeight,
scrolled = scrollY(),
viewed = scrolled + getViewportH(),
elTop = getOffset(el).top,
elBottom = elTop + elH,
// if 0, the element is considered in the viewport as soon as it enters.
// if 1, the element is considered in the viewport only when it's fully inside
// value in percentage (1 >= h >= 0)
h = h || 0;
return (elTop + elH * h) <= viewed && (elBottom) >= scrolled;
}
function init() {
var svgs = Array.prototype.slice.call( document.querySelectorAll( '#main svg' ) ),
svgArr = new Array(),
didScroll = false,
resizeTimeout;
// the svgs already shown...
svgs.forEach( function( el, i ) {
var svg = new SVGEl( el );
svgArr[i] = svg;
setTimeout(function( el ) {
return function() {
if( inViewport( el.parentNode ) ) {
svg.render();
}
};
}( el ), 250 );
} );
var scrollHandler = function() {
if( !didScroll ) {
didScroll = true;
setTimeout( function() { scrollPage(); }, 60 );
}
},
scrollPage = function() {
svgs.forEach( function( el, i ) {
if( inViewport( el.parentNode, 0.5 ) ) {
svgArr[i].render();
}
});
didScroll = false;
},
resizeHandler = function() {
function delayed() {
scrollPage();
resizeTimeout = null;
}
if ( resizeTimeout ) {
clearTimeout( resizeTimeout );
}
resizeTimeout = setTimeout( delayed, 200 );
};
window.addEventListener( 'scroll', scrollHandler, false );
window.addEventListener( 'resize', resizeHandler, false );
}
init();
})();
Can't something like this be working ?
$('.trigger').click(function(){
init();
})

Javascript function benchmarking

Today I have tried to write a simple prophiler utility for javascript functions.
The problem is that the more interaction I launch the more the system slows down so
I think that at some point I have a memory leak leading to this problem.
The experiment's code follows.
//Benchmark prototype
var Prophiler = (function( ){
var _benchMark = (function( func, duration, callBack ){
var _interval = 1000;
var _startMark = new Date().getTime();
var _now = _startMark;
var _count = 0;
var _rounds = 0;
var _throttle = (function( ){
while( ( _now - _startMark ) < _interval ){
func( );
_now = new Date().getTime( );
_count++;
}
_startMark = new Date().getTime();
_rounds++;
if( _rounds <= ( duration ) ){
window.setTimeout( _throttle, 25 );
return false;
}
else{
var _res = {};
_res.elapsedTime = duration;
_res.executions = _count;
_res.averageTime = _res.elapsedTime / _res.executions;
_res.averageTimeMs = _res.averageTime * 1000;
callBack( _res );
return false;
}
});
_throttle( );
});
return{
getProphile : function( params ){
_benchMark( params.subject, params.duration, params.callBack );
}
}
})( );
//Test
var sumNum = function( param1, param2 ){
var y = param1;
for( var i = 0; i < param2; i++ ){
y += param2;
}
};
Prophiler.getProphile({
subject: function( ){
sumNum( 10, 30 );
},
duration: 5,
callBack: function( data ){
console.log( data );
}
});
Just for the sake of comparison between the module pattern and a prototypal pattern. The performance improvement is more noticeable in Chrome but can be also noticed in firefox.
function BenchMark(fn, duration, callback){
this.fn = fn;
this.duration = duration;
this.callback = callback;
this.rounds = 0;
this.count = 0
this.timerId = null;
this.startMark = (new Date()).getTime();
this._execute = this.scope(this, 'execute');
this._execute();
}
BenchMark.prototype.scope = function(context, method){
return function(){
context[method].call(context);
}
}
BenchMark.prototype.execute = function(){
if(this.timerId !== null){
clearTimeout(this.timerId);
}
var count = 0, now = this.startMark;
while( (now - this.startMark) < 1000){
this.fn();
now = (new Date()).getTime();
count++;
}
this.startMark = (new Date()).getTime();
this.count += count;
this.rounds++;
if(this.rounds <= this.duration){
this.timerId = setTimeout(this._execute, 25);
return false;
}else{
var averageTime = this.duration / this.count;
this.callback({
elapsedTime : this.duration,
executions : this.count,
averageTime : averageTime,
averageTimeMs : averageTime * 1000
});
return false;
}
}
function Profiler(){
}
Profiler.prototype.benchmark = function(fn, duration, callback){
new BenchMark(fn, duration, callback);
}
function sumNum( param1, param2 ){
var y = param1;
for( var i = 0; i < param2; i++ ){
y += param2;
}
};
var profiler = new Profiler();
var profilerCalled = 0;
var intervalId = setInterval(function(){
console.log('Profiler: ', profilerCalled+1)
profiler.benchmark(function(){
sumNum(10, 30)
}, 5, function(result){
console.log(result)
});
profilerCalled++;
if(profilerCalled == 10){
clearInterval(intervalId);
console.log('stopped')
}
}, 10000);
In the end I found the error.
It was an algo misconception.
Obiviously each call adds a 25ms delay that get loosed since _startMark = new Date().getTime(); is called after comparison!
Now it works quite well!

Categories

Resources