Change images with different timeinterval using Js or jquery - javascript

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);

Related

Debounce return timer

I don't understand the principle of operation. I have a code in which I have to create a delay of 2 seconds during the twist but during the delay script should not work using the debounce script but for some reason it always returns some timer and not an answer from function that the debounce script accepts
function debounce(f, ms) {
let timer = null;
return function(...args) {
const onComplete = () => {
f.apply(this, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
};
}
var delay = false;
$('.window').on('mousewheel', function(event) {
var pozition = $(document).scrollTop();
var block2 = $(".main_step").offset().top
var elemId = $(this).attr('id'),
scrollDir = event.deltaY;
var indicatorL = $(".indicator_main").data("counter");
if (elemId == 'steps' && scrollDir < 0 && delay === false) {
if (indicatorL != "4") {
$("#sli-" + indicatorL).css("display", "none");
indicatorL = indicatorL + 1;
$("#sli-" + indicatorL).css("display", "block");
$(".indicator_main").data("counter", indicatorL);
$(".indicator_main").animate({
"left": "+=25%"
}, "slow");
$(".indicator_num").text("0" + indicatorL);
$(".step_nr").text("0" + indicatorL);
}
}
delay = true;
var f = function() {
var delay = false;
return delay;
};
delay = debounce(f, 2000);
console.log(delay);
});

Javascript Slideshow Speed

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

Starting Javascript intervals nonsynchronously and stop each after three runs

I have a function for letting blink a OpenLayer marker three times. The simplified version which only shows console messages:
function blink_three_times(layername){
var x = 0;
setTimeout(function() {
blink_in = setInterval(function() {
x = x+1;
if ( x === 3) {clearInterval(blink_in)};
console.log(layername + ' is visible');
}, 500);
}, 250);
blink_out = setInterval(function() {
if (x === 2) {clearInterval(blink_out)};
console.log(layername + ' is invisible');
}, 500);
};
It works fine, but if it is started multiple times before one has finished, the counter (x) exceeds 3 and the interval does not stop. How can I avoid that?
That is because you have funcions blink_in & blink_out in global scope. When you are calling it second time it overwrites the definitions of functions.
Define them using var to make them local.
var blink_in = setInterval(function() {..})
and
var blink_out = setInterval(function() {..})
DEMO
Your variables blink_in and blink_out are global ones so if you call the function multiple times they will override it and therefore cannot stop the interval properly.
Use them in your function scope by definining them with "var" in order to avoid the problem (see http://jsfiddle.net/cb0h8tst/)
function blink_three_times(layername){
var x = 0;
var blink_in, blink_out;
setTimeout(function() {
blink_in = setInterval(function() {
x = x+1;
if ( x === 3) {clearInterval(blink_in)};
console.log(layername + ' is visible');
}, 500);
}, 250);
blink_out = setInterval(function() {
if (x === 2) {clearInterval(blink_out)};
console.log(layername + ' is invisible');
}, 500);
};
Based on your last update question,
you could also make a more dynamic to keep track of the layers that are actually being blinked, a possible example
function Blinker(opt) {
var ts = {};
this.elementId = opt ? opt.elementId : undefined;
this.runs = (opt ? opt.runs : 3) || 3;
this.completed = (opt ? opt.completed : function() { }) || function() { };
this.start = function(arg) {
var timestamp = arg || this.elementId, that = this;
if (typeof ts[timestamp] !== 'undefined') {
console.log('Cannot run multiple times on same layer');
return;
}
ts[timestamp] = {
timestamp: timestamp,
count: 0,
element: document.getElementById(arg || this.elementId),
controller: this
};
setTimeout(function() {
ts[timestamp].showInterval = setInterval(that.setVisibility.bind(ts[timestamp], true), 500);
}, 250);
ts[timestamp].hideInterval = setInterval(this.setVisibility.bind(ts[timestamp], false), 500);
};
this.setVisibility = function(visible) {
this.element.style.visibility = visible ? 'visible' : 'hidden';
this.element.style.display = visible ? 'inherit' : 'none';
if (visible) {
this.count++;
}
if (!visible && this.count === 2)
{
clearInterval(this.hideInterval);
}
if (visible && this.count === 3)
{
clearInterval(this.showInterval);
this.controller.completed.apply(this.controller, [this.element.id]);
delete ts[this.timestamp];
}
};
}
var blinker = new Blinker({
elementId: 'blinker',
runs: 3,
completed: function(elementId) {
var log = document.getElementById('log');
log.innerHTML += '<p><strong>' + elementId + '</strong> has finished blinking</p>';
}
});
you could find the fiddle here: http://jsfiddle.net/q70w0kpx/

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!

Simple function call inside module, getting NaN, huh?

Here is the module i am working on:
var FeatureRotator = (function($,global) {
var self = {},
currentFeature = 0,
images = [],
imagePrefix = "/public/images/features/",
timer = null,
totalImages = 0,
initialFeature,
interval,
blendSpeed,
element = null,
img1 = null,
img2 = null;
function setVisibleImage(iid) {
$("#img1").attr('src',images[iid].src).css('opacity',1);
$("#img2").css('opacity',0);
$(".active").removeClass("active");
$("#f"+iid).addClass("active");
}
function setCurrentImage(id) {
currentFeature = id;
setVisibleImage(id);
}
function doHoverIn(position) {
if (currentFeature === position) {
self.pause();
} else {
setCurrentImage(global.parseInt(position, 10));
self.pause();
}
}
function doHoverOut(position) {
self.unpause();
}
self.init = function(options,callback) {
var i = 0,
tempImg = null;
interval = options.interval || 5000;
blendSpeed = options.blendSpeed || 500;
element = options.element;
initialFeature = options.initialFeature || 0;
img1 = $("<img/>").attr('id','img1');
img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);
$(element).append(img1).append(img2);
totalImages = $(".feature").size();
for (i = 0;i < totalImages; i++) {
tempImg = new global.Image();
tempImg.src = imagePrefix +"feature_" + i + ".png";
images.push(tempImg);
$("#f"+i).css('background-image',
'url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
.hover(doHoverIn($(this).attr('position'))
, doHoverOut($(this).attr('position'))
).attr('position',i);
}
setVisibleImage(initialFeature);
if (options.autoStart) {
self.start();
}
if (callback !== null) {
callback();
}
};
function updateImage() {
var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);
if (active === "#img1") {
$("#img2").attr('src',images[nextFeature].src);
$("#img2").fadeTo(blendSpeed, 1);
$("#img1").fadeTo(blendSpeed, 0);
} else {
$("#img1").attr('src',images[nextFeature].src);
$("#img1").fadeTo(blendSpeed, 1);
$("#img2").fadeTo(blendSpeed, 0);
}
$("#f"+currentFeature).removeClass("active");
$("#f"+nextFeature).addClass("active");
currentFeature = nextFeature;
}
self.start = function() {
currentFeature = initialFeature;
setVisibleImage(currentFeature);
timer = global.setInterval(function(){
updateImage();
}, interval);
};
self.pause = function() {
global.clearTimeout(timer);
};
self.unpause = function() {
timer = global.setInterval(function(){
updateImage();
}, interval);
};
return self;
}(this.jQuery, this));
And here is how it is used on the page:
<script type="text/javascript">
// ...
$(function() {
FeatureRotator.init({
interval:5000,
element:'#intro',
autoStart:true,
height:177,
blendSpeed:1000,
initialFeature:0
});
});
</script>
The problem is, when setVisibleImage is called from the init method, the value of iid is NaN. I've stepped through the debugger and verified that 'initialFeature' is 0 when the setVisibleImage function is called, but alas, the value doesn't make it over there.
Can anyone help me determine what the problem is? I've run the code through JSLint, and it came back clean.
UPDATE
Ok here is my updated code, which works now except the fading doesnt work, the image just flips to the next one and doesn't fade smoothly anymore:
var FeatureRotator = (function($,global) {
var self = {},
currentFeature = 0,
images = [],
imagePrefix = "/public/images/features/",
timer = null,
totalImages = 0,
initialFeature = 0,
interval,
blendSpeed;
function setVisibleImage(iid) {
$("#img1").attr('src',images[iid].src).css('opacity',1);
$("#img2").css('opacity',0);
$(".active").removeClass("active");
$("#f"+iid).addClass("active");
}
function setCurrentImage(id) {
currentFeature = id;
setVisibleImage(id);
}
function doHoverIn(obj) {
var position = global.parseInt(obj.target.attributes["position"].value,10);
if (currentFeature === position) {
self.pause();
} else {
setCurrentImage(global.parseInt(position, 10));
self.pause();
}
}
function doHoverOut() {
self.unpause();
}
self.init = function(options,callback) {
var i = 0,
tempImg = null,
element = null,
img1 = null,
img2 = null;
interval = options.interval || 5000;
blendSpeed = options.blendSpeed || 500;
element = options.element;
initialFeature = options.initialFeature || 0;
img1 = $("<img/>").attr('id','img1');
img2 = $("<img/>").attr('id','img2').css('opacity','0').css('margin-top',-options.height);
$(element).append(img1).append(img2);
totalImages = $(".feature").size();
for (i = 0;i < totalImages; i++) {
tempImg = new global.Image();
tempImg.src = imagePrefix +"feature_" + i + ".png";
images.push(tempImg);
$("#f"+i).css('background-image','url("'+imagePrefix+"feature_"+i+"_thumb.png"+'")')
.hover(doHoverIn, doHoverOut)
.attr('position',i);
}
setVisibleImage(initialFeature);
if (options.autoStart) {
self.start();
}
if (typeof callback === "function") {
callback();
}
};
function updateImage() {
var active = $("#img1").css('opacity') === 1 ? "#img1" : "#img2";
var nextFeature = (currentFeature === totalImages-1 ? 0 : currentFeature+1);
if (active === "#img1") {
$("#img2").attr('src',images[nextFeature].src);
$("#img2").fadeTo(blendSpeed, 1);
$("#img1").fadeTo(blendSpeed, 0);
} else {
$("#img1").attr('src',images[nextFeature].src);
$("#img1").fadeTo(blendSpeed, 1);
$("#img2").fadeTo(blendSpeed, 0);
}
$("#f"+currentFeature).removeClass("active");
$("#f"+nextFeature).addClass("active");
currentFeature = nextFeature;
}
self.start = function() {
currentFeature = initialFeature;
setVisibleImage(currentFeature);
timer = global.setInterval(function(){
updateImage();
}, interval);
};
self.stop = function() {
global.clearTimeout(timer);
};
self.pause = function() {
global.clearTimeout(timer);
};
self.unpause = function() {
timer = global.setInterval(function(){
updateImage();
}, interval);
};
return self;
}(this.jQuery, this));
Since you're getting NaN, I'm guessing it is actually taking place from this line:
.hover(doHoverIn($(this).attr('position'))
...which calls this:
setCurrentImage(global.parseInt(position, 10)); // note the parseInt()
...which calls this:
setVisibleImage(id);
So the position being passed to parseInt is coming from $(this).attr('position'), which is likely an value that can't be parsed into a Number, so you get NaN.
Check out the value of that attribute in first line of the block for the for statement.
for (i = 0;i < totalImages; i++) {
console.log( $(this).attr('position') ); // verify the value of position
// ...

Categories

Resources