Multiple instances of Setinterval - javascript

I have a little problem with my code.
I have it setup so that by default, a rotating fadeIn fadeOut slider is auto playing, and when a user clicks on a li, it will jump to that 'slide' and pause the slider for x amount of time.
The problem i have is that if the user clicks on multiple li's very fast, then it will run color1() multiple times with will start colorInterval multiple times. This gives a undesired effect.
So what i need help with, is figuring out how to reset my code each time a li is clicked, so whenever ColorClick is clicked, i want to make sure that there are no other instances of colorInterval before i start a new one.
Thanks in advance!
=================================
edit:
I now have another problem, i believe that i fixed the clearInterval problem, but now if you look at var reset, you'll see that it runs color1() each time a li is clicked, which runs multiple intervals, so i need to delete the previous instance of color1() each time it is called, to make sure that it doesnt repeat any code inside multiple times. So when a li is clicked delete any instances of color1()
or
i need that instead of running color1 in var reset, i will go straight to colorInterval instead of running color1() for each li clicked,
so run colorInterval after x amount of time in var reset.
function color1() {
var pass = 0;
var counter = 2;
var animationSpeed = 500;
var $colorContent = '.color-container-1 .color-content-container'
var $li = '.color-container-1 .main-color-container li'
$($li).on('click', function() {
colorClick($(this));
});
function colorClick($this) {
var $getClass = $this.attr("class").split(' ');
var $whichNumber = $getClass[0].substr(-1);
var $Parent = '.color-container-1 ';
pass = 1;
$($colorContent).fadeOut(0);
$($colorContent + '-' + $whichNumber).fadeIn(animationSpeed);
var reset = setTimeout(function() {
clearTimeout(reset);
pass = 0;
color1();
}, 10000);
}
var colorInterval = setInterval(function() {
if (pass > 0) {
clearInterval(colorInterval);
return; //stop here so that it doesn't continue to execute below code
}
$($colorContent).fadeOut(0);
$(($colorContent + '-' + counter)).fadeIn(animationSpeed);
++counter
if (counter === $($colorContent).length + 1) {
counter = 1;
}
}, 7000);
}

You could just clear the interval inside of the click event.
var colorInterval;
$($li).on('click', function() {
clearInterval(colorInterval);
colorClick($(this));
});
//Your other code
colorInterval = setInterval(function() {
//Rest of your code
});

One thing play with is jQuery animations have a pseudo class selector :animated when animation is in progress
if(!$('.your-slide-class:animated').length){
// do next animation
}

Related

Trying to make the clock function on click

And thanks for stopping by.
I've been trying to add a feature, or function, to a project that I'm working on, but I just can't wrap my head around it.
When my project loads I want the user to activate the time as soon as they move, or click, one of the orbs -- not as soon as the project loads. I know there's an onClick or click event, but I'm having trouble implementing it on the js code. I've gone as far as commenting-out or "greying" entire functions to test things out.
Here's some of the time code:
function clockStart() {
numberOfSecs = setInterval(function () {
seconds.text(`${second}`)
second = second + 1
}, 1000);
}
function rewindSec(seconds) {
if (seconds) {
clearInterval(seconds);
}
}
gameStart();
// GAMES BEGIN!!!
function gameStart() {
var cards = shuffle(listOfCards);
deckOfCards.empty();
match = 0;
Moves = 0;
moveNum.text("0");
ratingStars.removeClass("fa-angry").addClass("fa-star");
for (var i = 0; i < cards.length; i++) {
deckOfCards.append($('<li class="card"><i class="fab fa-' + cards[i] + '"></i></li>'))
}
sourceCard();
rewindSec(numberOfSecs);
second = 0;
seconds.text(`${second}`)
clockStart();
};
Here's a link to the project that I'm talking about:
Full Page View: https://codepen.io/idSolomon/full/RYPZNp/
Editor View: https://codepen.io/idSolomon/pen/RYPZNp/?editors=0010
WARNING: Project not mobile-friendly. At least not yet.
If someone can help me out with this, a thousand thank yous will come your way.
Thanks!
You can Change the event of starting the clock at another position
First remove the clockStart() function from the gameStart() method
seconds.text(`${second}`)
//clockStart();
if have added an Extra variable to detect if the clock is started or not
var isClockStarted=false;
The following code will start the timer when a card is clicked:
var sourceCard = function () {
deckOfCards.find(".card").bind("click", function () {
if(!isClockStarted)
clockStart();
The Bellow Code will check if the timer is started or not.
function clockStart() {
if(!isClockStarted){
isClockStarted=true;
numberOfSecs = setInterval(function () {
seconds.text(`${second}`)
second = second + 1
}, 1000);
}
}
I have found that you are not stopping the timer even after the game finishes
If canceled a game it starts timer again //toCheck

How do I make elements trigger to appear one after another, with a small interval?

I have a series of four elements. The first of which (#pro1) will appear on scrolling to a particular point on the page (this currently works), and the following three will trigger to appear one after another, with a small changeable interval in between each.
Any help would be greatly appreciated! A huge thank you in advance!
Here is the code for the first element, just needing to make the others appear after this one appears (#pro2, #pro3, #pro4, etc)
<script>
$(window).one("scroll", function() {
$('#pro1').each(function () {
var topOfWindow = $(window).scrollTop(),
bottomOfWindow = topOfWindow + $(window).height();
var imagePos = $(this).offset().top;
if(imagePos < bottomOfWindow-200 && imagePos >= topOfWindow-500){
$(this).addClass('bigEntrance2');
}else{
$(this).removeClass('bigEntrance2');
}
});
});
</script>
The key is using setInterval to call repeatedly the function that will create (or show if they are already created) the next elements.
It is important to not forget to clear the interval when the job is done.
Without the html and the css is difficult to realise exactly what you want to achieve, but from the next example you shouldn't have problems to update yours.
var interval = null;
var elementId = 1;
var numElements = 4;
var delay = 1000; //ms
$(document).ready(function()
{
//your first "pro1" element show up
var element = "<div>Im the pro" + elementId + " element!</div>";
$('body').append(element);
//in that moment we set the interval
interval = setInterval(show_next_element, delay);
});
function show_next_element()
{
//increment the counter elementId
elementId++;
//create the next element
var element = "<div>Im the pro" + elementId + " element!</div>";
//add it to the DOM
$('body').append(element);
//when our last element is created we clear the interval
if(elementId >= numElements)
clearInterval(interval);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope it helps!

a setInterval within a for loop in Javascript

My code below needs to put in a setInterval within a for loop. I basically need to put in a 10 second pause between the next iteration of the for loop. This is for a very basic script which shows banners in a div for 10 seconds before moving onto the next one. It existing setInterval is code I got off another website as I ran out of options. Any help? And if you don't mind explaining the logic to me so that I know for the future :)
$("document").ready(function() {
// bannerChange
function bannerChange(banner,div,milliseconds) {
var length = banner.length;
for(i=0;i<length;i++) {
(function(i) {
setInterval(function() {
var url = banners[i].url;
var img = banners[i].image;
$("#"+div).html("<a href='"+url+"' target='_Blank'><img src='www/images/banners/"+img+"' /></a>");
},milliseconds)
})(i);
}
}
function showBanner(bannerName, bannerDiv, milliseconds) {
var url = "www/scripts/ajax/getBanners.php";
$.post(url, {name: bannerName}, function(data) {
if(data.response == true) {
bannerChange(data.banners,bannerDiv,milliseconds);
}
});
}
// Run banners
showBanner("Test Banner","test",10000);
});
Here's an updated version based on the comment:
// Start by getting the banners:
var banners = [];
var currentBanner;
function getBannersFromServer(...) {
// TODO: make ajax call to server for banners
// push the banners into a queue for later
for (var i in bannerFromServer) {
banners.push(bannersFromServer[i]);
}
}
// Then run through them:
function showNextBanner() {
// advance to next banner
currentBanner++
// go back to the beginning after the last banner is displayed
if(currentBanner >= banners.length) currentBanner = 0;
// pull a banner out of the queue
var banner = banners[currentBanner];
// TODO: Show the banner in the div
// do it again in 10 seconds
showNextBanner();
}
// start it all
getBannersFromServer();
getNextBanner();
Try using:
.delay()
Here is a great example of this function in use!
Try this
var i=0;//Global Variable
function bannerChange(banner, div, milliseconds) {
var length = banner.length;
setInterval(function() {
var url = banners[i].url;
var img = banners[i].image;
$("#"+div).html("<a href='"+url+"' target='_Blank'><img src='www/images/banners/"+img+"' /></a>");
i++;
if(i >= length) i=0;//To reiterate from first
},milliseconds);
}
Hope this solves your problem.

How to show last 5 seconds when timing is running out?

Hi i am using Javascript set timeout to run a certain function.
How do i display the last 10 seconds of the timeout when it is nearing the end?
var a = setTimeout('someFunction()', 10000);
Is it able to display something using the value that it store into the variable?
Thanks
I have created a small demo for you,
http://jsfiddle.net/praveen_prasad/DYaan/1/
<div id="target" style="display:none">
target
</div>
var target,
allotedTimeForWork=100 /*you can change this*/
;
var handler = setTimeout(function(){
if(!target)
{
target=document.getElementById('target');
}
target.style.display="block";
startTicker();
}, allotedTimeForWork);
function startTicker()
{
var counter=10;
var tickerHandler= window.setInterval(function(){
if(counter>0)
{
//cache target
target.innerHTML="you have "+counter +" seconds left";
counter--;
}
else
{
target.innerHTML="time over";
clearInterval(tickerHandler);
}
},1000);
}
It is not possible to directly get the remaining time of a Timeout.
You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.
I would use two timeouts.
The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.
Take a look here: http://jsfiddle.net/VCAnm/
HTML:
<span id="aaa">10</span>
JavaScript:
setInterval(function() {
var elem = document.getElementById('aaa');
elem.innerHTML = elem.innerHTML - 1;
}, 1000);
set 2 timers one for the timeout and another for the warning
var warn_time = 5000;
var function_name = 'someFunction()';
var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);
function warnFunction(function_name, time) {
alert('only ' + time + ' seconds left'); //use a div or whatever to display
var b = setTimeout(function_name, time);
}

setInterval() not working after clearInterval() in this Javascript code

I have been ripping my hair off a couple of nights now with this problem:
I'm trying to create an expanding div with JavaScript. Here's the part of the HTML file:
<div id="bbc_div" class="bbc_div" style="display:none; height:200px;">
<input type="button" value="Show BBC" id="bbc_button" onclick="onclickBBC('bbc_div')" />
And here's the magical non-working JavaScript file:
var maxHeight = 100;
var curHeight = 1;
var wait = 5;
var timerID = new Array();
function onclickBBC(obj) {
if (document.getElementById(obj).style.display == "none") {
slideDown(obj);
}
else {
document.getElementById(obj).style.display="none"
}
}
function slideDown(obj) {
document.getElementById(obj).style.height="1px";
document.getElementById(obj).style.display="block";
timerID[obj] = setInterval("slideDownExec(\"" + obj + "\")", wait);
return;
}
function slideDownExec(obj) {
if (curHeight <= maxHeight) {
curHeight++;
document.getElementById(obj).style.height=curHeight + "px";
}
else {
endSlide(obj);
}
return;
}
function endSlide(obj) {
clearInterval(timerID[obj]);
return;
}
When I reload the page, div expands once to its right height. But, if I push the button without reloading page again after it has hided again, it doesn't work. display:block; works, but setInterval() isn't starting. So this happens after clearInterval() has executed. Why is clearInterval() killing my setInterval() permanently?
The timer is running, you just need to reset a variable:
function slideDown(obj)
{
document.getElementById(obj).style.height = "1px";
curHeight = 1;
I would use jQuery for this, it's a LOT easier.
You have an issue with curHeight not being set to 1 at the top of slideDown. If this doesn't happen, the if statement at the top of slideDownExec will only work the first time.
Additionally, does JavaScript allow non-integer array indexes?
> a['i'] = 4
4
> a
[]
> a['i']
4
What you're actually doing is adding a property called i to the array object. You might as well use an empty object rather than an array.

Categories

Resources