How to disable a button with a timed loop? - javascript

i'm trying to disable a button for 6 seconds while in a loop but so far I can't quite figure it out.
var disabledStartTimer = setInterval(disabledTimer, 1000);
function disabledTimer() {
var start = 0;
if (start > 6) {
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
attack.disabled = true;
} else {
attack.disabled = false;
start++;
};
}
attack = the button I click to attack.

var start = 0;
if (start > 6){
Clearly this will always go into the else. You set the variable to 0 and then test if it's greater than 6... it isn't. You likely wanted this to be a global, move it outside of the function.

Related

How to setInterval once inside foreach using javascript

I need to set interval once for each slider element inside array when "if" statement is true but my code sets unlimited interval every time "if" statement is true. it is my js code:
const sliders = [realestateSlider,carsSlider,spectechnicSlider,motorcyclesSlider,partsSlider,beautySlider,clothesSlider,bestsellersSlider,topproductsSlider,salesSlider];
function checkIfIntoView(sliders){
sliders.forEach(function(slider,index){
if(slider.getBoundingClientRect().top <= window.innerHeight || document.documentElement.innerHeight){
setInterval(function(){slider.scrollLeft += scrollWidth;},1000);
}
});
}
window.addEventListener('wheel',function(event){ checkIfIntoView(sliders); });
Since you call the checkIfIntoView function in event listener, event listner will tiger that function each and every time a on wheel event occur. So if you want to call the checkIfIntoView function once the wheel event triggered, use a Boolean variable.
let ran = false;
function checkIfIntoView(sliders){
if (!ran) {
ran = true
sliders.forEach(function(slider,index){
if(slider.getBoundingClientRect().top <= window.innerHeight || document.documentElement.innerHeight){
setInterval(function(){slider.scrollLeft += scrollWidth;},1000);
}
});
}
}
Assuming that those are all Elements in the sliders Array, maybe you're looking to do something like:
const sliders = [realestateSlider, carsSlider, spectechnicSlider, motorcyclesSlider, partsSlider, beautySlider, clothesSlider, bestsellersSlider, topproductsSlider, salesSlider];
onscroll = e=>{
requestAnimationFrame(()=>{
let b, t, l;
for(let n of sliders){ // n is each node
b = n.getBoundingClientRect(); t = b.top; l = b.left;
if(t+b.height > -1 && t <= innerHeight && l+b.width > -1 && l <= innerWidth){
console.log('in view');
}
else{
console.log('not in view');
}
}
});
}
Note that you can always leave window. off of any property of window.
I'm not sure exactly what you are asking... But if you want to scroll until slider.getBoundingClientRect().top >= window.innerHeight then you could write your function like this:
const sliders = [realestateSlider,carsSlider,spectechnicSlider,motorcyclesSlider,partsSlider,beautySlider,clothesSlider,bestsellersSlider,topproductsSlider,salesSlider];
function checkIfIntoView(sliders){
sliders.forEach(function(slider,index){
let interval = setInterval(function(slider){
if (slider.getBoundingClientRect().top <= window.innerHeight || document.documentElement.innerHeight) {
slider.scrollLeft += scrollWidth;
} else {
clearInterval(interval);
}
}, 1000);
}
window.addEventListener('wheel',function(event){ checkIfIntoView(sliders); });
That way the interval will be cleared after the criteria is met. Keep in mind setInterval will continue to run until it is cleared via clearInterval

clearInterval does not stop the interval operation

I'm working on a timer, and would like the setInterval() operation to terminate when the counter reaches zero. Further, I would like the function to be "turned off" if you will, so that I can reset the value that is fed into the timer, without the timer starting to decrement again.
When I configure the code like this:
function countdown(){
var intervalKill = setInterval(function(){
var start = document.getElementById("startValue").innerHTML;
if (start > 1){
var time_left = start - 1;
document.getElementById("startValue").innerHTML = time_left;
} else if (start === 1) {
clearInterval(intervalKill)
}
}, 1000);
}
I get it running perfectly well, however if it reaches 1, and I reset the timer, it will start counting down instantly again.
When I code it like this:
function countdown(){
var intervalKill = setInterval(function(){
var start = document.getElementById("startValue").innerHTML;
if (start > 1){
var time_left = start - 1;
document.getElementById("startValue").innerHTML = time_left;
} else if (start === 1) {
clearInterval(intervalKill);
break;
}
}, 1000);
}
The function just does not run at all. Can someone shed some light on what is going on here and how to get it to work?
function countdown(){
var intervalKill = setInterval(function(){
var start = document.getElementById("startValue").innerHTML;
if (start > 1){
var time_left = start - 1;
document.getElementById("startValue").innerHTML = time_left;
} else if (+start === 1) {
clearInterval(intervalKill);
// break; <-- not necessary
}
}, 1000);
}
Either parse the start to integer using unary + or parseInt or use == instead of === since the latter checks for type information as well.
innerHTML returns a string.

setting a time delay between two frame when animation a sprite sheet

This is my jsfiddle :http://jsfiddle.net/Z7a5h/
As you can see the animation of the sprite sheet when the player is not moving is too fast so I was trying to make it slow by declaring two variable lastRenderTime: 0,RenderRate: 50000
but my code is not working and it seem I have a misunderstanding of the algorithm I am using so can anyone lay me a hand to how can I fix it?
if (!this.IsWaiting) {
this.IsWaiting = true;
this.Pos = 1 + (this.Pos + 1) % 3;
}
else {
var now = Date.now();
if (now - this.lastRenderTime < this.RenderRate) this.IsWaiting = false;
this.lastRenderTime = now;
}
Yes, your logic is wrong. You were using the wrong operator < instead of >. Also, you needed to update the lastRenderTime only when the condition is statisfied, otherwise it keeps getting updated and the value of now - this.lastRenderTime never ends up becoming more than 20 or so.
if (!this.IsWaiting) {
this.IsWaiting = true;
this.Pos = 1 + (this.Pos + 1) % 3;
}
else {
var now = Date.now();
if (now - this.lastRenderTime > this.RenderRate) {
this.IsWaiting = false;
this.lastRenderTime = now;
}
}
Here is your updated fiddle.

Avoid javascript's variables reset when user uses back and foward

Well,
I Have a countdown timer, and I'm facing the following problem:
My countdown starts at 90 seconds. If the user waits until it reaches 2 seconds, for example, then he goes back using browser's button and after goes forward (backing to the same page), the countdown restarts at 90 seconds, not at 2 as I need, because when the timer reaches 0 I "click" at a button which post the form.
I know I need to handle the back and forward button and set my variable with the new value but I don't have any idea how can I do it. Any help will be great.
My code is below:
var count = 90;
var screenCount = count;
var newCount = 0;
function countFunction() {
if (screenCount != 0) {
var minutes = Math.floor(count / 60);
var seconds = count - minutes * 60;
if (count > 60){
if (seconds < 10)
seconds = "0" + seconds;
screen = minutes + "m:" + seconds + "s";
$('.timer').css('width',"120px")
}
else{
if (count < 10)
screen = "0" + count;
else
screen = count + "s";
$('.timer').css('width',"60px")
}
document.getElementById('tempo').innerHTML = screen;
if (count == 0) {
set('temporizador', screenCount);
$(":submit").removeAttr("disabled");
$('#responder').click();
}
if (count != 0) {
set('temporizador',screenCount - count );
count = count - 1;
setTimeout("countFunction()", 1000);
}
}
else {
document.getElementById('tempo').innerHTML = '∞';
set('temporizador', newCount);
newCount++;
setTimeout("countFunction()", 1000);
}
}
When the user presses back a whole new page is loaded, with an entirely new Javascript context. If you want to pass information from the context of one page to the context of another, there are several ways to do it.
In your particular situation, using LocalStorage is the easiest:
// count down 90 seconds, including page navigation on this site
var count = +localStorage.getItem('timerCount') || 90;
function countDown() {
count--;
localStorage.setItem('timerCount', count);
if (count<0) window.clearInterval(myInterval);
}
var myInterval = window.setInterval(countDown, 1000);
Suggestion by #DmitryVolokh
In this example i stored the remaining time in localStorage. If you want to track the elapsed time from a particular moment, you would be better served to store the starting time instead and compute the difference.
You use local storage for this as suggested above but there is the slight issue that some older browsers don't support localStorage: http://caniuse.com/#search=local%20storage
Since you are only storing a single number you could also use a cookie:
var match, count;
if (match = /timerCount=(\d+);/.exec(document.cookie)) {
count = match[1];
} else {
count = 90
}
function countDown() {
count--;
document.cookie = 'timerCount=' + count + ';';
if (count<0) window.clearInterval(myInterval);
}
var myInterval = window.setInterval(countDown, 1000);
You can use the onbeforeunload javascript event to see when the users leave the page, and then act as you want : changing the window.location to redirect the user (and give additional parameters like your timer), or prevent him from leaving the page.
You can also create a cookie or use localstorage to store the timer and get it back next time user comes to your page.

for loop does not stop at each index

var switchTabs = function(index, el) {
//alert("Call SwitchTabs");
ribbon.slideTo(index);
ribbon.currentSlideIndex = parseInt(index, 10);
//console.log(ribbon.currentSlideIndex);
dojo.query('.ibm-slider-wrapper #ibm-thumb-slider-tabs li.ibm-active').removeClass('ibm-active');
dojo.query(el).addClass('ibm-active'); //applies class to current active li
//fixTabHeight(index == 4);
}
This below section of the auto scroll runs and does not stop 1 index at a time. It jumps straight to 6 and so my slider moves from 0 to 6th position. I want it to move 1 at a time after 8 seconds.
How can I make it stop each index and run the swapTabs(a, b); and then trigger an increment in the index variable inside autoScroll?
I tried using setInterval() but it still does function the way I want. Ideally I would like to use Switch statement for each index and trigger swapTabs inside setInterval so I can manage the timer for individual index key. Any help is highly appreciated.
var autoScroll = function(){
//alert("Inside AutoScroll");
//var tabCount = $('.ibm-slider-wrapper #ibm-thumb-slider-tabs li');
for(var i = 0; i < 6; i++) {
var tabsIndex = $('.ibm-slider-wrapper #ibm-thumb-slider-tabs li a');
switchTabs(parseInt(tabsIndex[i].getAttribute('rel'), 10), tabsIndex[i].parentNode);
console.log(tabsIndex[i]);
}
}
autoScroll();
Use setTimeout and have the function call itself:
var i = 0, interval = 8000, iterations = 6;
var autoScroll = function(){
// function body here
i++;
console.log("Iteration #" + i);
if (i < iterations) {
setTimeout(autoScroll, interval);
}
}
// start first run
autoScroll();
Your code just goes from index 0 to 5 in rapid succession (within ms of each other) and the browser probably doesn't display anything until your script finishes on index 6.
If you want it to stop and show each tab, then you need to use something like setTimeout() and advance one tab each time the timer fires.
(function() {
var indexCntr = 0;
var tabsIndex = $('.ibm-slider-wrapper #ibm-thumb-slider-tabs li a');
function autoScroll() {
if (indexCntr < 6) {
switchTabs(parseInt(tabsIndex[index].getAttribute('rel'), 10), tabsIndex[i].parentNode);
++indexCntr;
setTimeout(autoScroll, 5000); // set the proper delay time here
}
}
autoScroll();
})();

Categories

Resources