Run a jQuery .click event on an element every 5 seconds repetitively - javascript

I have an element which I want to be "clicked" every 5 seconds, does something, and then after 5 seconds it gets clicked again, does something, ect'.
So I used setTimeout, which does the job for the 5 seconds thing:
(found the example here: How to hide a div after some time period?)
And there's the jQuery event .trigger which I found here: JQuery automatic click after 4 sec
I tried looping it using 'for' and I got a .click event that happens after the first 5 seconds, and then uses the .click event again and again without the 5 seconds pause: http://jsfiddle.net/WTJgt/417/
In general, I built my first jQuery rotator :)!
with right and left buttons - and I want it to move a slide after x seconds by clicking it "without clicking".
This is my .click event code for the "next" element button:
// variables
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
$(".r-arrow").click(function(){
moveInPixles = ( rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
}
});

setInterval(function () {
$(".r-arrow").click();
}, 5000);
Edit:
Use setInterval and clearInterval so that you can reset the interval on button click. Your code needs refactoring because you can't really use it as it is.
var intervalId;
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
autoRotate();
function autoRotate() {
intervalId = window.setInterval(function () {
rotateStuff();
}, 5000);
}
function rotateStuff() {
moveInPixles = (rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq(" + rotCounter + ")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq(" + rotCounter + ")").css('background-color', 'yellow');
}
}
$('.r-arrow').on('click', function () {
window.clearInterval(intervalId);
rotateStuff();
autoRotate();
});

Dont do a click, but just trigger the javascript function every five seconds. by triggering a click you also activate all other functions listening to the event and some might be in conflict with your code or used by other libraries.
You can use setInterval() to do so.
Your code should looks like this :
// variables
var rotCounter = 0;
var moveInPixles = 0;
var nunSlides = 4; // Enter the number of slides
var myFunction = function(){
moveInPixles = ( rotCounter + 1) * 746 * -1;
moveInPixles += 'px';
$(".rotator-container").css('margin-left', moveInPixles);
rotCounter++;
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
if (rotCounter == nunSlides) {
rotCounter = 0;
$(".rotator-container").css('margin-left', 0);
$(".dot").css('background-color', 'white');
$(".dot:eq("+rotCounter+")").css('background-color', 'yellow');
}
});
$(".r-arrow").click(myFunction);
setInterval(myFunction, 5000);
It is important to assign setInterval to a variable then you will be able to stop it using clearInterval()
var intervalID = window.setInterval(code, delay);
Then when you need to stop it :
window.clearInterval(intervalID)

Would do the trick
var rightArrowIntervalId = setInterval(function(){
$(".r-arrow").trigger('click');
}, 5000);
In your click event add at
$(".r-arrow").click(function(){
window.clearInterval(rightArrowIntervalId);
// will destroy existing interval
moveInPixles = ( rotCounter + 1) * 746 * -1;
.....
// will create new interval in 5 seconds
rightArrowIntervalId = setInterval(function(){
$(".r-arrow").trigger('click');
}, 5000);
});

I don't fully understand the question, but if you want to call a function every 5 seconds rather than just once then use setInterval().

Use setInterval function instead of setimeout
$( function() {
$('#login').click(function() {
alert('login button clicked');
});
setInterval(function() {
$('#login').trigger('click');
}, 500);
});
check updated JSFIDDLE

Related

jQuery setTimeout wait

I have a simple JS function, to animate this form progress Bar:
https://codepen.io/himanshu/pen/syLAh
This is how my function looks like now:
function makeAnimate() {
var i = 1;
$('.progress .circle').removeClass().addClass('circle');
$('.progress .bar').removeClass().addClass('bar');
setInterval(function() {
$('.progress .circle:nth-of-type(' + i + ')').addClass('active');
$('.progress .circle:nth-of-type(' + (i-1) + ')').removeClass('active').addClass('done');
$('.progress .circle:nth-of-type(' + (i-1) + ') .label').html('✓');
$('.progress .bar:nth-of-type(' + (i-1) + ')').addClass('active');
$('.progress .bar:nth-of-type(' + (i-2) + ')').removeClass('active').addClass('done');
i++;
if (i==0) {
$('.progress .bar').removeClass().addClass('bar');
$('.progress div.circle').removeClass().addClass('circle');
i = 1;
}
//Here i would do if i equal 3 wait in the loop extra 100ms
if (i == 1) {
setTimeout(function(){
}, 100);
}
//Here i would do if i equal 3 wait in the loop extra 200ms
if (i == 3) {
setTimeout(function(){
}, 200);
}
}, 800);
}
It's not working. How can I do that to wait exrta millisecs?
Thank you!
What you need is extract the animation function and pass it to interval, save the interval as a scoped variable so you can clear it and assign new value with different timeout.
Here is a working proof of concept:
$(function() {
var i = 0;
var timeout = 1000; // 1 Second
$('.timeout').text(timeout);
$('.i').text(i);
var animate = function() {
if (i === 2) {
timeout = 6000; // 6 Seconds
clearInterval(interval);
interval = setInterval(animate, timeout);
}
if (i === 3) {
timeout = 1000; // Back to 1 second
clearInterval(interval);
interval = setInterval(animate, timeout);
}
if (i >= 7) {
// Remember to clear the interval once your steps complete, otherwise it will run forever
clearInterval(interval);
}
i++;
$('.timeout').text(timeout);
$('.i').text(i);
}
var interval = setInterval(animate, timeout);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Timeout: <span class="timeout"></span>
<br /> I: <span class="i"></span>

Converting a manual slideshow to automatic

I followed a tutorial and created a simple manual loop slideshow. I'm trying to make it so it changes the slide automatically even if the prev/next buttons aren't clicked. I tried a crude approach by setting a delay between automatic click events on the "next" button but for some reason it clicks it only once and stops. My js knowledge is very limited and can't figure it out, any input is appreciated. This is the script so far:
$(function() {
var ul = $(".slider ul");
var slide_count = ul.children().length;
var slide_width_pc = 100.0 / slide_count;
var slide_index = 0;
var first_slide = ul.find("li:first-child");
var last_slide = ul.find("li:last-child");
last_slide.clone().prependTo(ul);
first_slide.clone().appendTo(ul);
ul.find("li").each(function(indx) {
var left_percent = (slide_width_pc * indx) + "%";
$(this).css({"left":left_percent});
$(this).css({width:(100 / slide_count) + "%"});
});
ul.css("margin-left", "-100%");
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
});
function slide(new_slide_index) {
var margin_left_pc = (new_slide_index * (-100) - 100) + "%";
ul.animate({"margin-left": margin_left_pc}, 400, function() {
if(new_slide_index < 0) {
ul.css("margin-left", ((slide_count) * (-100)) + "%");
new_slide_index = slide_count - 1;
}
else if(new_slide_index >= slide_count) {
ul.css("margin-left", "-100%");
new_slide_index = 0;
}
slide_index = new_slide_index
});
}
});
Here is an approach to make it sliding automatically...
But if user clicks on prev/next, it holds the automatic feature for a defined "idle" time.
It need two lines added to your click handlers:
var autoEnabled = true; // ADDED
$(".slider .prev").click(function() {
console.log("prev button clicked");
slide(slide_index - 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
$(".slider .next").click(function() {
console.log("next button clicked");
slide(slide_index + 1);
autoEnabled = false; // ADDED
disabledCount = 0; // ADDED
});
And this to cyclically slide or check if it can re-enable itself.
// ----------------- Automatic sliding interval with "idle time" to re-enable on user click
var idleTime = 5000; // Time without manual click to re-enable automatic sliding.
var autoSlideDelay = 1000; // Time between each slide when automatic.
var disabledCount = 0;
var autoSlide = setInterval(function(){
if(autoEnabled || disabledCount >= idleTime/autoSlideDelay ){
disabledCount = 0;
autoEnabled = true;
slide(slide_index + 1);
}else{
disabledCount++;
}
},autoSlideDelay);
var break_auto_slide = false;
function auto_silde()
{
if(break_auto_slide)
{
break_auto_slide = false;
return;
}
slide(slide_index + 1);
setTimeout(auto_silde,1000 /* time in ms*/);
}
setTimeout will call the function in a specified timeout in milliseconds.
Variable break_auto_slide - set it to true to stop the automatic slide. Next time the function is called it will return without setting a new timer and will reset this variable so auto mode can be turned on again.

How to change the speed of setInterval in real time

I would like to know how to change the speed of setInterval in real time e.g:
if (score < 10)
repeater = setInterval(function() {
spawnEnemy();
}, 1000);
if (score => 10)
repeater = setInterval(function() {
spawnEnemy();
}, 500);
I know this method doesn't work, but is there a way that I can achieve this some other way?
jsFiddle Demo
There is no way to change the interval speed itself once running. The only way to do it is to have a variable for the speed, and then clear the interval and start a new one with the new speed.
var speed = 500;
var changeSpeed = speed;
repeater = setInterval(repeaterFn, speed);
function repeaterFn(){
spawnEnemy();
if( changeSpeed != speed ){
clearInterval(repeater);
speed = changeSpeed;
repeater = setInterval(repeaterFn, speed);
}
}
function changeRepeater(){
changeSpeed = 700;
}
Another way would be to just use setTimeout rather than setInterval. Do the check every time so you can keep your speed logic in a seperate function.
var game_over = false;
var score = 0;
function getSpeedFromScore(score)
{
if (score > 20) {
game_over = true;
}
if (score < 10) {
return 1000;
} else {
return 500;
}
}
function spawnEnemyThenWait() {
if (!game_over) {
spawnEnemy();
var speed = getSpeedFromScore(score);
setTimeout(spawnEnemyThenWait, speed);
}
}
JS Fiddle http://jsfiddle.net/bq926xz6/
You can use clearInterval:
if (score < 10) {
clearInterval(repeater);
repeater = setInterval(spawnEnemy, 1000);
}
if (score => 10) {
clearInterval(repeater);
repeater = setInterval(spawnEnemy, 500);
}
But it depends on the context. If this snippet is executed more often, than it has to be, you will need some kind of mechanism to prevent it from resetting your interval all the time.
But there is (as I wrote in the comment to the question) no way to use clearInterval and change the interval itself. At least not without replacing it by a new interval as shown above.
You can use a game loop and track the spawn state in an enemy class:
// press f12 so see console
function Enemy() {
this.spawned = false;
this.spawnOn = 20;
this.tick = function () {
this.spawnOn = this.spawnOn - 1;
if (this.spawnOn == 0) {
this.spawned = true;
}
}
this.goBackToYourCage = function () {
this.spawnOn = Math.floor(Math.random() * 50) + 1;
this.spawned = false;
}
}
var enemy = new Enemy();
window.setInterval(function () {
enemy.tick();
if (enemy.spawned) {
console.log('spawned');
enemy.goBackToYourCage();
console.log('Next spawin in :' + enemy.spawnOn);
}
}, 100);
http://jsfiddle.net/martijn/qxt2fe8y/2/

setInterval doesnt tigger inner script on first time run

Maybe I'm not properly understanding setInterval but I have made a kind of slideshow script, as below:
var i = 0;
setInterval(function() {
$('.slide').fadeOut('slow').delay(200);
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i++;
if(i == 5){
i = 0;
}
}, 4000);
This works, except for the first run - no slides will display for the first 4 seconds.
See Fiddle here: http://jsfiddle.net/vpa89snf/6/
Is there anyway I can trigger whats inside the setInterval function when it runs the first time round?
Use setTimeOut instead of setInterval for better performance, inspect the sample below:
Here is working jsFiddle.
var i = -1;
var totalSlide = $('.slide').length-1;
var slideTimer = 0;
function nextFrame() {
i == totalSlide ? i = -1 : i;
i++;
$('.slide').fadeOut(200);
$('.slide').eq(i).fadeIn(200);
slideTimer = setTimeout(nextFrame,4000);
}
$('#holder').addClass('isAni');
nextFrame();
// play / pause animation
$('#holder').click(function() {
if ( $(this).hasClass('isAni') ) {
$(this).removeClass('isAni');
clearTimeout(slideTimer);
}else{
$(this).addClass('isAni');
nextFrame();
}
});
You need to run the function and not wait for the 4 first seconds:
var i = 0;
function doSomething() {
$('.slide').fadeOut('slow').delay(200);
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i = (i + 1) % 5;
}
$document.ready(function () {
setInterval(doSomething, 4000);
doSomething(); // run it!
});
JSFIDDLE.
This is how setInterval is executed. It runs your function after x milliseconds set as 2nd parameter.
What you have to do in order to show the first slide is to have the 1rst slide fadein like below:
var i = 0;
$('.slide:eq(' + i + ')').fadeIn('slow').delay(2000);
i++;
setInterval(function() {
...
}, 4000);

Timer not running more than once

For some reason when I run the below script for the first time, the timer doesn't activate again for a second time, any idea why?
var timer = 0;
$(document).ready(function() {
$('#search').keypress(function() {
if(timer == 0) { $('#sel').html('<iframe src="search.php?p=' + $('#search').val() + '"></iframe>'); }
timer = 1;
setTimeout('timer = 0;', 2000);
});
});
Regards
Matthew
setTimeout only runs once. You probably want setInterval.
$('#search').keypress(function() {
if(timer == 0) { setTimeout('clearTimeout(this);timer = 0;', 2000); $('#sel').html('<iframe src="search.php?p=' + $('#search').val() + '"></iframe>'); }
timer = 1;
});
Running the timer inside it fixed it well :)

Categories