change content based on timer - javascript

The click functions I made change the content. But, whenever I use setinterval or settimeout, the functions run 1 time and then run again immediately without using the delay.
What am I doing wrong?
$(document).ready(function() {
$('.seashellcontainertwo').hide();
var settimer = 1;
$('.seashellcontainer').click(function() {
settimer = 0;
$('.seashellcontainer').hide();
$('.seashellcontainertwo').show();
});
$('.seashellcontainertwo').click(function() {
settimer = 0;
$('.seashellcontainertwo').hide();
$('.seashellcontainer').show();
});
if (settimer == 1) {
setInterval(function() {
$('.seashellcontainertwo').hide();
$('.seashellcontainer').show();
}, 3000);
setInterval(function() {
$('.seashellcontainertwo').show();
$('.seashellcontainer').hide();
}, 3000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="seashellcontainer">seashellcontainer</div>
<div class="seashellcontainertwo">seashellcontainertwo</div>

I suppose,this is what you were trying to achieve in intervals, Not sure about click events though. Further clarification will help.
$(document).ready(function() {
var seaShellContainerTwo = $('.seashellcontainertwo');
var seaShellContainer = $('.seashellcontainer');
seaShellContainerTwo.hide();
var settimer = 0;
setInterval(function() {
if (settimer === 1) {
seaShellContainerTwo.hide();
seaShellContainer.show();
settimer = 0;
} else {
seaShellContainerTwo.show();
seaShellContainer.hide();
settimer = 1;
}
}, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="seashellcontainer">seashellcontainer</div>
<div class="seashellcontainertwo">seashellcontainertwo</div>

Related

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

Set up a counter for a JavaScript timer loop based on number of images

What I would like to do is set each BannerImg element to display: none one at a time using a timer setup. Then, once I have looped through all BannerImg elements, I want to reset them to display: block. It's basically like a image rotator that I'm trying to make...but right now, I'm not sure how to target each BannerImg element one at a time--I am targeting them all at once, which is not what I want to do.
jQuery.noConflict();
(function($) {
$(document).ready(function() {
var BannerCount = $('BannerImg').length;
var intervalID = window.setInterval(function() {
$('.BannerImg').toggleClass("HideBannerImg");
}, 2000);
});
}(jQuery));
Use .eq(index). You'll probably want to cache your collection to make it faster:
(function($) {
$(document).ready(function() {
var $banners = $('.BannerImg');
var index = 0;
var intervalID = window.setInterval(function() {
$banners.eq(index).toggleClass("HideBannerImg");
index++;
// Check to see if we've hit the end of the collection
// If so, stop the interval.
if (index === $banners.length) {
clearInterval(intervalID);
}
}, 2000);
});
}(jQuery));
I'm kind of guessing you want something like this (correct me if I'm wrong):
setInterval(function () {
if ($('.BannerImg').last().hasClass('HideBannerImg')) {
$('.HideBannerImg').first().removeClass('HideBannerImg');
} else {
$('.BannerImg').not('.HideBannerImg').first().addClass('HideBannerImg');
}
}, 1000);
jQuery.noConflict();
(function($) {
$(document).ready(function() {
var iterator = 0;
var BannerCount = $('BannerImg').length;
var intervalID = window.setInterval(function() {
$('.BannerImg').eq(iterator).toggleClass("HideBannerImg");
iterator += 1;
if (iterator === BannerCount.length - 1) {
clearInterval(intervalID);
$('.BannerImg').removeClass("HideBannerImg");
}
}, 2000);
});
}(jQuery));
try this recursive function
var images = $('.BannerImg').each();
var hideImage = function(index){
images[index].toggleClass("HideBannerImg");
if(index < images.length-1)
setTimeout(function(){
hideImage(index++);
}, 2000);
}
hideImage(0);
After calling $('.BannerImg') you need to use jQuery's each to loop over each of the elements it selected.
jQuery.noConflict();
(function($) {
$(document).ready(function() {
$('.BannerImg').each(function() {
var $this = $(this);
var intervalID = window.setInterval(function() {
$this.toggleClass("HideBannerImg");
}, 2000);
});
});
}(jQuery));
Just note that this will toggle on and off over and over until you clear the interval.

JavaScript - setInterval only running once [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 6 months ago.
http://jsfiddle.net/689nauny/
setInterval() is only running once... WTF is going on?
SO is asking for more details but providing a JSFiddle is about as descriptive as I can be? I've tried using an anonymous function and now a callback. I just don't get it? :-/
HTML
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<div id="qanda-timer-container">
<div class="qanda-timer">
<span id="qanda-time-remaining"></span>
</div>
</div>
JS
function intervalFunc(thinkingTime, answerTime)
{
jQuery('#qanda-time-remaining').text(''+(thinkingTime - 1));
}
function enableTimer(time)
{
var intervalID;
var hasThinkingTime = true;
var thinkingTime = time;
var hasAnswerTime = true;
var answerTime = 10;
if(hasThinkingTime && hasAnswerTime)
{
setInterval( intervalFunc(thinkingTime, answerTime), 1000);
}
setTimeout(function(){
clearInterval(intervalID);
}, time * 1000);
}
enableTimer(30);
You need to wrap the interval handler in a function:
intervalId = setInterval( function() { intervalFunc(thinkingTime, answerTime) }, 1000);
Your code as posted is calling the function and passing the result to setInterval(). The interval timer isn't running at all!
After you do that, you'll need to fix the problem of maintaining the descending time value. Currently you pass the variable as a parameter and subtract one from it, but you don't update the original variable.
function intervalFunc(thinkingTime, answerTime)
{
jQuery('#qanda-time-remaining').text(''+(thinkingTime));
}
Then change the setInterval setup:
intervalId = setInterval( function() { intervalFunc(--thinkingTime, answerTime) }, 1000);
}
Your code doesn't work because of this line:
setInterval( intervalFunc(thinkingTime, answerTime), 1000);
Change it into this:
setInterval( function(){
intervalFunc(thinkingTime, answerTime);
}, 1000);
You need to provide a function to setInterval(), while you are providing undefined.
This is why it doesn't run.
Running code:
function enableTimer(time)
{
var elem = jQuery('#qanda-time-remaining'), interval = setInterval( function(){
if(time/1 == time/1 && time) //if(!isNaN(time) && time>0)
{
elem.text( time-- );
}
else
{
clearInterval(interval);
elem.text(0);
}
}, 1000);
}
enableTimer(5);
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<div id="qanda-timer-container">
<div class="qanda-timer">
<span id="qanda-time-remaining"></span>
</div>
</div>
I have simplified your code to the extreme and is so much easy to read.
You can set a new parameter to which you provide a function that will run after the time is up:
function enableTimer(time, fn)
{
var elem = jQuery('#qanda-time-remaining'), interval = setInterval( function(){
if(time/1 == time/1 && time) //if(!isNaN(time) && time>0)
{
elem.text( time-- );
}
else
{
clearInterval(interval);
elem.text(0);
if( fn instanceof Function )//if fn is a function
{
fn();//call it
}
}
}, 1000);
}
enableTimer(5, function(){ alert('Time\'s up!'); });
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<div id="qanda-timer-container">
<div class="qanda-timer">
<span id="qanda-time-remaining"></span>
</div>
</div>
Here is a working example: http://jsfiddle.net/689nauny/3/
Your issue was partly with scope and in general how you decremented the count down variable
var thinkingTime = undefined;
var answerTime = undefined;
var intervalID = undefined;
function enableTimer(time) {
var hasThinkingTime = true;
thinkingTime = time;
var hasAnswerTime = true;
answerTime = 10;
if (hasThinkingTime && hasAnswerTime) {
intervalID = setInterval(function () {
thinkingTime -= 1;
jQuery('#qanda-time-remaining').text('' + (thinkingTime));
}, 1000);
}
setTimeout(function () {
clearInterval(intervalID);
}, time * 1000);
}
enableTimer(30);

JQuery Auto Click

I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example

need to reset the function how do i do it

I want to reset this flash in between so that i need not have to wait till the end to restart the flash, how do i reset this?
function flash() {
var arrayId = 0,
splitSet = $('#text_original').html().split(" "),
splitSetLength = splitSet.length;
function flashWord() {
$("#flash_word").html(splitSet[arrayId]);
arrayId += 1;
var t = setTimeout(remove, 1000);
}
function remove() {
if (arrayId < splitSetLength) {
$("#flash_word").html(" ");
flashWord();
} //else reset_flash();
}
flashWord(); }
please see the http://jsfiddle.net/HcDfS/
Make the timer variable a global one and cancel the time-out on it (with clearTimeout()). Then, hide #flash_word.
I took the liberty of re-implementing your fiddle:
var timer, words;
function startFlashing() {
words = $("#source").text().split(" ");
showNextWord(0);
}
function stopFlashing() {
clearTimeout(timer);
$("#banner").text("");
}
function showNextWord(index) {
$("#banner").text(words[index]);
index++;
if (index < words.length) timer = setTimeout(function () {
showNextWord(index);
}, 1000);
else $("#banner").text("");
}
​
With HTML:
<p id="source">This is the text to be flashed.</p>
<button onclick='startFlashing()'>Start Flashing!</button>
<button onclick='stopFlashing()'>Stop Flashing!</button>
<p id="banner"></p>​
And it's here: http://jsfiddle.net/CZnVc/6/

Categories

Resources