call EventListener with setInterval() - javascript

My task is to make a few pictures in a slideshow and if don't click a button for forward and back (id = right and id = left in my code) in 5 seconds it should automaticly move forward , i succeeded but i feel that the code is to much.
var counter = 1;
$('#left').on('click', function peter() {
clearInterval(time);
time = setInterval(function () {
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
},3000);
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter--;
if (counter === 0) {
counter = 3;
}
id = '#' + counter;
$(id).attr('class', 'visible');
});
$('#right').on('click', function () {
clearInterval(time);
time = setInterval(function () {
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
},3000);
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
});
var time = setInterval(function peter() {
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter++;
if(counter === 4){
counter = 1;
}
id = '#' + counter;
$(id).attr('class', 'visible');
},3000);
So the problem as you can see is that i pretty much decleared my setInterval() 3 times, 1st in my code and then i declear it every time in my eventListeners to reset it. My question is this: Is there any way to declear it once and call the eventListeners like time(call listnener for id='right') and then in the event listners to just reset it like clearInterval(a); without having to retype it.

var counter = 1;
var time;
function intervalFunction(offset)
{
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter += offset;
if(counter > 4)
counter = 1;
else if(counter < 1)
counter = 4;
id = '#' + counter;
$(id).attr('class', 'visible');
}
function startInterval(offset){
if(time)
clearInterval(time);
intervalFunction(offset);
time = setInterval(function () {
intervalFunction(1);
},3000);
}
$('#left').on('click', function peter() {
startInterval(-1);
});
$('#right').on('click', function () {
startInterval(1);
});
startInterval(1);

I'm not sure if this would do it. Didn't actually test it first. But you could combine all of the redundant work into a single function that you would call. I added the clicktype parameter to the function and use it to determine if it should increment or decrement the value of counter.
I also modified the setInterval to setTimeout, as in this setup the call is cleared and reset each time anyway.
var counter = 1;
var timeoutdelay = 3000;
function OnChangeSlide(clicktype) {
clearTimeout(time);
var id = '#' + counter;
$(id).attr('class', 'hidden');
counter = counter + (clicktype=='#left' ? -1 : 1);
if (counter === 0) {
counter = 3;
} else if (counter === 4) {
counter = 0;
}
id = '#' + counter;
$(id).attr('class', 'visible');
time = setTimeout(function() { OnChangeSlide('#right'); }, timeoutdelay);
}
$('#left').on('click', function() { OnChangeSlide('#left'); } );
$('#right').on('click', function() { OnChangeSlide('#right'); } );
time = setTimeout(function(){ OnChangeSlide('#right'); }, timeoutdelay);

Related

Why i can't change i in setTimeout() function?

function turn(id, player) {
let value = parseInt($('#' + id).attr('data-value'));
showValue();
id = parseInt(id);
for (let i = 1; i <= value; i++) {
let newId = id + i;
setTimeout(function () {
if (player == 'p1') {
let value = parseInt($('#' + newId).attr('data-value'));
if (newId == 14) {
let mainValue = parseInt($('#main-1').attr('data-value'));
$('#main-1').attr('data-value', mainValue + 1);
// i want to add i++; but nothing happen
} else {
$('#' + newId).attr('data-value', value + 1);
}
} else {
let value = parseInt($('#' + newId).attr('data-value'));
if (newId == 7) {
let mainValue= parseInt($('#main-2').attr('data-value'));
$('#main-2').attr('data-value', mainValue + 1);
//here too
} else {
$('#' + newId).attr('data-value', value + 1);
}
} showValue();
}, i * 500);
}
}
when i console.log the i in that spot, nothing happened.
but when i change i outside setTimeout function, it works.
how can i fix that?
You should use setInterval instead of setTimeout in your case.
function turn(id, player) {
let value = parseInt($("#" + id).attr("data-value"));
showValue();
id = parseInt(id);
let i = 1;
const timer = setInterval(function () {
if (player == "p1") {
let newId = id + i;
let value = parseInt($("#" + newId).attr("data-value"));
if (newId == 14) {
let mainValue = parseInt($("#main-1").attr("data-value"));
$("#main-1").attr("data-value", mainValue + 1);
// i want to add i++; but nothing happen
} else {
$("#" + newId).attr("data-value", value + 1);
}
} else {
let value = parseInt($("#" + newId).attr("data-value"));
if (newId == 7) {
let mainValue = parseInt($("#main-2").attr("data-value"));
$("#main-2").attr("data-value", mainValue + 1);
//here too
} else {
$("#" + newId).attr("data-value", value + 1);
}
}
showValue();
i++;
if (i > value) {
clearInterval(timer);
}
}, 500);
}
function turn(id, player) {
let value = parseInt($('#' + id).attr('data-value'));
showValue();
id = parseInt(id);
let i = 1;
for (i = 1; i <= value; i++) {
let newId = id + i;
setTimeout(function () {
if (player == 'p1') {
let value = parseInt($('#' + newId).attr('data-value'));
if (newId == 14) {
let mainValue = parseInt($('#main-1').attr('data-value'));
$('#main-1').attr('data-value', mainValue + 1);
i++;
} else {
$('#' + newId).attr('data-value', value + 1);
}
} else {
let value = parseInt($('#' + newId).attr('data-value'));
if (newId == 7) {
let mainValue= parseInt($('#main-2').attr('data-value'));
$('#main-2').attr('data-value', mainValue + 1);
i = i + 1
} else {
$('#' + newId).attr('data-value', value + 1);
}
} showValue();
}, i * 500);
}
}
I think this here should work as it worked for me! Have a nice day :)

Reset JS timer when window goes out of focus

Been twisting my head for a long time over this and can't seem to get it to work.
Basically trying to reset the timer when the window goes out of focus for longer than 30 seconds.
I'd be thankful for any solution that works.
Regards, Will.
window.onData = function(data) {
if (data.setDisplay == true) {
$("#container").css('display', 'flex');
$("body").fadeIn(1000);
var counter = 90;
var c = 90;
var i = setInterval(function(){
$(".loading-page .counter h1").html("YOU HAVE " + c + " SECONDS LEFT UNTIL RESPAWN");
$(".loading-page .counter hr").css("width", c + "");
counter--;
c--;
if(counter == 0) {
$(".loading-page .counter h1").html("YOU MAY DO /RESPAWN");
$(".loading-page .counter p").html("DON'T FORGET THE NEW LIFE RULE!");
clearInterval(i);
}
}, 1000);
} else {
$("#container").css('display', 'none');
$("body").css('display', 'none');
}
}
window.onload = function(e) {
window.addEventListener('message', function(event) {
onData(event.data)
});
}
Perhaps you mean this?
Not tested but has enough snippets to be moved around
const onData = function(data) {
if (data.setDisplay == true) {
$("#container").css('display', 'flex');
$("body").fadeIn(1000);
let tId = setInterval(function() {
$(".loading-page .counter h1").html("YOU HAVE " + counter + " SECONDS LEFT UNTIL RESPAWN");
$(".loading-page .counter hr").css("width", counter);
counter--;
if (counter == 0) {
$(".loading-page .counter h1").html("YOU MAY DO /RESPAWN");
$(".loading-page .counter p").html("DON'T FORGET THE NEW LIFE RULE!");
clearInterval(tId);
}
localStorage.setItem("counter",counter);
}, 1000);
} else {
$("#container").hide()
$("body").hide()
}
}
let counter;
const getCounter = function() {
counter = localStorage.getItem("counter");
counter = counter === null ? 90 : +counter; // continue from where it was
const now = new Date().getTime()
const blurred = sessionStorage.getItem("blurred");
blurred = blurred ? +blurred : 0;
if (blurred && (now-blurred)/1000) >30) counter = 0;
};
$(function() {
$(window).on('message', function(event) {
onData(event.data)
});
$(window).on("blur",function() {
sessionStorage.setItem("blurred",new Date().getTime())
})
});
$(window).on("focus",getCounter )

Counting up and down to specified number in order in Javascript

I am trying to get this script to count up to a specified number and back down to a specified number as follows: 19200, 38400, 57600, 76800, 96000, 76800, 57600, 38400, 19200 — repeatedly. So far this is what I have but I cannot seem to make it count down in the order above, it restarts from 19200 again.
$(function() {
var seconds = 19200;
var timerId = setInterval(function() {
seconds = seconds + 19200;
$("#counter").text(seconds);
if (seconds > "76800") {
clearInterval(seconds);
seconds = seconds - "19200";
}
}, 500);
});
A little issue with the logic, the condition
if (seconds > "76800") {
would always try to keep the seconds above 76800.
Rather you would want a flag to track the direction of the count. Check out below:
UPDATED:
Working demo at
JSFiddle
$(function () {
var increment = 19200;
var seconds = increment;
var countUp = true;
var timerId = setInterval(function () {
$("#counter").text(seconds);
if (countUp) {
seconds += increment;
} else {
seconds -= increment;
}
if (countUp && seconds > increment*4) {
countUp = false;
} else if (!countUp && seconds <= increment) {
countUp = true;
}
}, 500);
});
Check the below function
$(function() {
var seconds = 19200;
action = 'add';
var timerId = setInterval(function() {
$("#counter").text(seconds);
if (seconds == 96000) {
action = 'remove';
} else if (seconds == 19200) {
action = 'add'
}
if (action == 'add')
seconds += 19200;
else if (action == 'remove')
seconds -= 19200;
}, 500);
});
I think this is a little more elegant
var increment = 19200,
seconds = increment;
var timer = setInterval(function() {
console.log(seconds);
seconds += increment;
if (seconds > 76800 || seconds < 19200) {
increment *= -1;
}
}, 500);
jsfiddle

Time to start only after button click

http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/

Simple jquery counter

Hi all i have got this really simple jquery counter
var count = 10;
countdown = setInterval(function(){
$("p.countdown").html(count + " seconds remaining!");
if (count == 0) {
alert('done');
}
count--;
}, 1000);
How can i make it reset after it gets to 0 instead of going into minus???? so it keep iterating.
http://jsfiddle.net/isimpledesign/mSQdp/
any help
To reset and repeat, put count = 11; after the alert('done');.
To stop, put clearInterval(countdown); after the alert('done');.
Try this
var count = 10;
countdown = setInterval(function(){
$("p.countdown").html(count + " seconds remaining!");
count--;
if (count == 0) {
count = 10;
}
}, 1000);
var count = 10,
countdown = setInterval(function () {
$("p.countdown").html(count + " seconds remaining!");
if (count == 0) {
count = 11; //since it will be reduced right after this
//clearInterval(countdown); <-- use this if you want to stop
alert('done');
}
count--;
}, 1000);
Just like this:
if (count == 0)
count = 11
You might also want to look at the jQuery countdown plugin
...
if (count == 0) {
alert('done');
count = 11;
}
...

Categories