this is my javascript code only work on click event and i want to make this auto slideshow. please help me i have no knowledge how to do it..
var wflSliders = ({});
var wflSlider = new Class({
Implements:[Options,Events],
initialize:function(options){
this.setOptions(options);
if(this.options.ribbon_behavior == 'scroll'){
this.wrapper = $('rand_products_wfl_'+this.options.id);
if(this.wrapper){
this.ribbon = this.wrapper.getElement('.jspw_ribbon');
this.scroll_r = this.wrapper.getElement('.jspw_scroll');
this.lt = this.wrapper.getElement('.jspw_ribon_button_lt');
this.rb = this.wrapper.getElement('.jspw_ribon_button_rb');
this.blocks = this.wrapper.getElements('.jspw_prod');
var blockSize = this.blocks[0].getComputedSize();
var dim = (this.options.orientation == 'hor')?'x':'y';
if(this.options.effect_block == 'single'){
this.offset=(dim=='x')?blockSize.totalWidth:blockSize.totalHeight;
}
One way to approach is that you can use a built-in function called setInterval in Javascript and after wrapping your code in a function call it in the interval you desire to have your slideshow speed.
Like the following:
setInterval(function(){
slideShow(); // Every second the function is called
},1000);
Check the documentation here for more understanding: MDN Documentation for setInterval function
UPDATE: Givi just proved to me (in the comments of my answer) that my answer was not right. It has high risk that you use my suggested approach and better to use setTimeout recursively like this:
function slideShow() {
setTimeout(function() {
slideShow();
}, 1000);
}
you can us slide show plugin. Good luck
Related
I thought an interval just delayed the function, but as it turns out it actually loops.
When I include some function that stops the interval after the deletor function ends it doesn't trigger that and I still get Test logged to the console.
document.addEventListener("DOMContentLoaded", function(event) {
let fullURL = window.location.href;
//let fullURL2 = window.location.host + window.location.pathname;
if (fullURL === "https://net.adjara.com/" ||
fullURL === "https://net.adjara.com/Home") {
var timer = setInterval(deletor, 5);
function deletor() {
timer;
var slider = document.querySelector("#slider-con");
var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
var bannerMiddle = document.querySelector("#MainContent > iframe");
var bannerRandom = document.querySelector("#MainContent > div:nth-child(3)");
if (slider) {
slider.parentNode.removeChild(slider);
}
if (bannerTop) {
bannerTop.parentNode.removeChild(bannerTop);
}
if (bannerMiddle) {
bannerMiddle.parentNode.removeChild(bannerMiddle);
}
if (bannerRandom) {
bannerRandom.parentNode.removeChild(bannerRandom);
}
function stopInterval() {
clearInterval(timer);
}
console.log("Test");
/*if ()
clearInterval(timer);*/
};
} else {
return false;
}
});
What you're looking for is setTimeout. It runs only once.
setTimeout(deletor, 5);
Also, you don't need to write timer variable inside of your closure like you would in Python. Javascript captures everything that's inside of lexical scope.
The code you provided works ¯\_(ツ)_/¯
Maybe the problem is coming from what triggers stopInterval()
But as mentioned in comments / other answers, you might be better off with another method
I wouldn't recommend using setTimeout in your case, because it looks like you are simply waiting for some DOM elements to be loaded. The problem with the timeout is that you can't know for sure how fast is the computer that will run your code. Maybe a bad quality phone with an outdated software that will need way more time to run your code than when you test on your personal computer, and that will not have the elements loaded by the time your function will be executed.
jQuery
For this reason, and since you tagged your question with jQuery I think you could use $(elementYouWaitForTheDOM2beLoaded).ready(function2execute) for each element you are watching instead of a having a loop that waits for the elements to be loaded (documentation for "ready" function)
Vanilla JS
And if you want to do it in pure JS it would be document.querySelector(elementYouWaitForTheDOM2beLoaded).on('load', function2execute))
I'm making a game for a school project. The premise is that there will be enemies coming from the right side of the screen, and you will have to kill them. I've managed to create them so they are shown, but i can't manage to make them not come in at the same time.
Any tips on how i should go on with this?
(Sorry if this is badly formulated, i am very new to these things)
I've tried different ways of achieviving my goal trough using the elapsedTime function but i can't seem to make it work in the slightest.
function createEnemy() {
for(var i = 0; i < antallFiender; i++) {
var nyFiende = document.createElement("img");
nyFiende.setAttribute("src", "tenor.gif");
nyFiende.setAttribute("class", "zombie");
nyFiende.style.top = Math.floor(Math.random()*800) + "px";
barnetEl.appendChild(nyFiende);
}
var zombieEl = document.querySelectorAll(".zombie");
}
You can use JavaScript setInterval function. With this function you can pass a callback in the first parameter, and a time interval (in miliseconds) as the second parameter, that is the time between the calls of your callback. So it will be something like this:
function createEnemy() {
var nyFiende = document.createElement("img");
nyFiende.setAttribute("src", "tenor.gif");
nyFiende.setAttribute("class", "zombie");
nyFiende.style.top = Math.floor(Math.random()*800) + "px";
barnetEl.appendChild(nyFiende);
var zombieEl = document.querySelectorAll(".zombie");
}
setInterval(createEnemy, 1000);
This way, every 1 second your function will be called to create one enemy.
If you want to stop the function from being called, you should assign the interval to a variable, so you can use clearInterval to stop it, like this:
var enemyInterval = setInterval(createEnemy, 1000);
clearInterval(enemyInterval);
Hope it helps you.
Im relatively new to JS coding, and can't get this little number to work. Can anyone tell me what I'm doing wrong?
My JavaScript is:
incrementScroll = function() {
window.scrollBy(0, 3) ;
}
startScrollLoop = function() {
scrollLoopId = setInterval( "incrementScroll", 5) ;
}
stopScrollLoop = function() {
clearInterval( scrollLoopId ) ;
}
And my HTML is:
<button onclick="startScrollLoop()">AUTO SCROLL</button>
<button onclick="stopScrollLoop ()">STOP SCROLL</button>
Again, many thanks for help. New to all of this and need to make a project work by morning.
Cheers.
The first argument to setInterval() should be a function reference, or non-ideally, a string to be eval()'d, which would be a complete function call with (). So remove the quotes:
// Pass the reference to incrementScroll,
// not a quoted string containing its name.
scrollLoopId = setInterval(incrementScroll, 5);
And to clear the scroll, you will need to define scrollLoopId at a higher scope with var.
// Define outside the function so it is available
// in scope of the stopScrollLoop() function when needed...
var scrollLoopId;
var startScrollLoop = function() {
scrollLoopId = setInterval( incrementScroll, 5) ;
}
Jsfiddle demo
(uses a slower scroll speed to give you a chance to click the stop button in the middle of the text)
Note that it is good practice to use the var keyword with each of these. even though they would end up at window scope anyway (assuming they're not being defined inside another function).
// Define with var
var incrementScroll = function() {
window.scrollBy(0, 3);
}
I have some code (below) which I wrote for a small piece of text to fade in out through a cycle of around 4 paragraphs. It works, but whenever I bring up the Web Inspector, it just tells me that it's an 'Anonymous function'. This is really annoying. Does anyone know how to fix it?
Btw, the bit that it hightlights as an anonymous function is:
slides[current].fadeOut("slow");
slides[target].fadeIn("slow");
The whole extract of code is here:
$(document).ready(function() {
var About = {
init: function() {
var slide_images = $('#widget p')
slides = new Array(),
delay = 5,
current = 0;
slide_images.each(function(index) {
current = index;
slides.push($(this));
});
var interval = setInterval(function() {
target = (current < (slides.length - 1)) ? current + 1 : 0;
slides[current].fadeOut("slow");
slides[target].fadeIn("slow");
current = target;
}, delay * 750);
}
}
About.init();
});
I made a jsfiddle here.
Because it is an anonymous function, as opposed to a named function.
One potential solution could be to roll the code into a named function and reference that function by named for the init option.
I began writing a simple animation class in JS, which utilizes Zepto.js animation capabilities but adds timeline-like capability to it.
The timeline itself is a simple array, that executes functions embedded in it when it's play() function is called:
play : function(callback){
for(var i=0; i<Animator.timeline.buffer.length; i++){
Animator.timeline.buffer[i].animation();
}
if(callback){
callback();
}
}
The setTimeout goes directly in the animation:
alpha : function(parameters, callback, delay){
var target = parameters.target;
var duration = parameters.duration;
var easing = parameters.easing;
var value = parameters.value;
if(delay){
setTimeout(function(){run();},delay*1000);
} else {
run();
}
function run(){
$(target).anim({opacity:value},duration,easing);
if(callback){
callback();
}
}
}
So basically, the timeline just runs the setTimeout-ed functions which are placed in it's buffer array.
This approach works (almost) as intended with WebKit animations, but i've run into a few problems when doing image sequences (animations using setInterval which change the image's src). As JS timers don't guarantee execution in their appointed time, sometimes animations run late, likely because of the embedded setInterval inside them.
Any ideas on how to solve this? I am aware that embedding all animations as callbacks inside one another would solve much of the issues, but i don't really know how to do that from inside the timeline loop. Also, it would quickly become an unreadable mess of callbacks if I call all functions in a direct manner (without using the timeline).
For reference, the sequence function of my animator class:
sequence : function(parameters, callback, delay){
var target = parameters.target;
var path = parameters.path;
var baseName = parameters.baseName;
var digits = parameters.digits;
var extension = parameters.extension;
var frames = parameters.frames;
var loop = parameters.loop;
if(parameters.interval){
var _interval = parameters.interval
} else {
var _interval = 15;
}
var currentFrame = 0;
var imageUrl = '';
var fileName = baseName;
for(var i=0; i<=digits; i++){
fileName+='0';
}
if(delay){
setTimeout(function(){runSequence();},delay*1000);
} else {
runSequence();
}
function runSequence(){
var interval = setInterval(function(){
if(currentFrame >= frames){
currentFrame = 0;
if(!loop) {
clearInterval(interval);
if(callback){
callback();
}
}
} else {
imageUrl = path+fileName.substring(0, fileName.length-currentFrame.toString().length)+currentFrame+"."+extension;
$(target).attr('src',imageUrl);
currentFrame++;
}
},_interval);
}
}
Also, a sample of an animation created by using this class:
Animator.timeline.append(function(){
Animator.alpha({'target':'#logo', 'value':1, 'duration':1, 'easing':'ease-out' });
});
Animator.timeline.append(function(){
Animator.sequence({'target':'#sequence', 'path':'images/sequences/index/', 'baseName':'nr1_', 'digits':3, 'extension':'png', 'frames':50},'',1.5);
});
Animator.timeline.append(function(){
Animator.scale({'target':'#text', 'width':.5, 'height':.15, 'duration':1, 'easing':'ease-in-out'},'',3.2);
});
Animator.timeline.append(function(){
Animator.alpha({'target':'#link', 'value':1, 'duration':1,'easing':'ease-out'},'',4.7);
});
Animator.timeline.play();
As an additional note, I was aiming to create something similar to GreenSock in AS3, if that helps.
Thanks.
Accurate setInterval can be simulated by compensating for the time it takes to execute every iteration, maybe this gist I wrote can help you:
https://gist.github.com/1185904