I need to stop the execution of the function PadanjeFun when ZivotBroj==-5.
I tried jQuery stop() Method, clearInterval(myVar) and return but it's not working.
I need to stop all tree animation (#cepJedan, #cepDva, #cepTri) when ZivotBroj==-5
Here is the code:
var PadanjeFun=function(){
if(bod==4) //Change speed when bod reaches the number
{
q=4;
}
else if(bod==7)
{
q=3;
}
$(document).ready(function(){
setInterval(function(){ //Neka zakasni prvi cep
$("#cepJedan").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepJedan").style.top = "150px";
ZivotOduzmi();
document.getElementById("Broj").innerHTML = bod;
});
}, 1000); //Let it start after 1 sec
});
$(document).ready(function(){
setInterval(function(){
$("#cepDva").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepDva").style.top = "150px";
ZivotOduzmi();
document.getElementById("Broj").innerHTML = bod;
});
}, 9000); //Let it start after 9 sec
});
$(document).ready(function(){
setInterval(function(){
$("#cepTri").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepTri").style.top = "150px";
ZivotOduzmi();
PadanjeFun();
console.log("Q je: "+q);
document.getElementById("Broj").innerHTML = bod;
});
}, 3000); //Let it start after 3 sec
});
}
Here is the ZivotOduzmi function if that helps anyone:
var ZivotOduzmi=function(){
if((document.getElementById("cepJedan").style.top == "850px") && (document.getElementById("box").style.left == "550px") || (document.getElementById("box").style.left == "980px"))
{
zivotBroj--;
console.log("Imate jos ovoliko zivota: "+zivotBroj);
var element = document.getElementById('Zivot');
element.style.width = (element.offsetWidth - 100) + 'px';
}
else if((document.getElementById("cepDva").style.top == "850px") && (document.getElementById("box").style.left == "120px") || (document.getElementById("box").style.left == "980px"))
{
zivotBroj--;
console.log("Imate jos ovoliko zivota: "+zivot);
var element = document.getElementById('Zivot');
element.style.width = (element.offsetWidth - 100) + 'px';
}
else if((document.getElementById("cepTri").style.top == "850px") && (document.getElementById("box").style.left == "120px") || (document.getElementById("box").style.left == "550px") )
{
zivotBroj--;
console.log("Imate jos ovoliko zivota: "+zivotBroj);
var element = document.getElementById('Zivot');
element.style.width = (element.offsetWidth - 100) + 'px';
}
}
You need to assign setInterval to a variable like:
var anim3;
$(document).ready(function(){
anim3 = setInterval(function(){
$("#cepDva").animate({
top: "850px",
},1000 * q, function(){
BodRacunaj();
document.getElementById("cepDva").style.top = "150px";
ZivotOduzmi();
document.getElementById("Broj").innerHTML = bod;
});
}, 9000); //Let it start after 9 sec
});
and call
clearInterval(anim3);
$("#cepDva").stop();
Related
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 )
The problem is that It calls the var intervalLeft and intervaRight at the same time. When it is moving right I want the intervalLeft not to work & vice versa.
When It reaches startPosition 100 it activates the intervalLeft and when it reaches startPosition 0 it activates intervalRight infinite.
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var intervalLeft = setInterval(frameLeft, 10);
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalRight);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.right = startPosition + "%";
}
}
}
</script>
This is the exercise:
Below this, you have a div that needs to move left to right using JS for the motion. Make it reach the end in 2 seconds, then return in 5s. Repeat that forever.
Have updated your code. Use below
<div id="moveAnimation" class="block"></div>
</div>
<script>
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10);
var rightTimer = true;
var leftTimer = false;
var intervalLeft;
function frameRight() {
if(!rightTimer){
rightTimer = true;
intervalRight = setInterval(frameRight,10)
return;
}
if (startPosition >= 100) {
rightTimer = false;
clearInterval(intervalRight);
frameLeft();
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if(!leftTimer){
leftTimer = true;
intervalLeft = setInterval(frameLeft,10)
return;
}
if (startPosition <= 0) {
leftTimer = false;
clearInterval(intervalLeft);
frameRight();
} else {
startPosition -= 2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
After testing some more i've found the answer with fewer lines of code.
var elem = document.getElementById("moveAnimation");
elem.addEventListener("click", movingImage);
function movingImage() {
var startPosition = 0;
var intervalRight = setInterval(frameRight, 10); //1
function frameRight() {
if (startPosition >= 100) {
clearInterval(intervalRight);
intervalLeft = setInterval(frameLeft, 10);
} else {
startPosition += 0.5;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
function frameLeft() {
if (startPosition <= 0) {
clearInterval(intervalLeft);
intervalRight = setInterval(frameRight, 10);
} else {
startPosition -= 0.2;
document.getElementById("moveAnimation").style.left = startPosition + "%";
}
}
}
</script>
this works how it Should. In the original code I posted the clearInterval was not linked to an actual intervalID
I am working on a animation there are four buttons with directions that can be pressed multiple times, and Run button. When Run buttons is pressed it should execute all the movements.
I have a catch 22 type of problem where ether events are fired forever and animation never stops or it only is being run once.
I tried multiple solutions and now settled on triggers, program works in a way where moves are being added to array and then fired in for loop, firing mechanism is setting triggers that would fire for that direction in short intervals.
Below code is done only for button right to reproduce the problem just click it twice and press run and you will see what I mean, I have also added console debugs that indicate the problem, and a Jsfiddle https://jsfiddle.net/0rxs9jpy/1/
If you want to reproduce where it only fires once check this fiddle https://jsfiddle.net/0rxs9jpy/2/ or uncomment line //if (r) return;
var moves = [];
leftpx = 0;
downpx = 0;
uppx = 0;
rightpx = 0;
var up = function() {
moves.push('up')
}
var down = function() {
moves.push('down')
}
var left = function() {
moves.push('left')
}
var right = function() {
moves.push('right')
}
document.addEventListener("moveRight", function(e) {
});
document.addEventListener("stopRight", function(e) {
console.log(e.detail);
clearInterval(e.detail);
});
var Run = function() {
for (var i = 0; i < moves.length; i++) {
if (moves[i] == 'up') {
document.getElementById('square').style.top = setInterval(myMove(), 3000);
};
if (moves[i] == 'left') {
document.getElementById('square').style.left = myMove3()
};
if (moves[i] == 'down') {
document.getElementById('square').style.top = myMove2()
};
if (moves[i] == 'right') {
//if (r) return;
var r = setInterval(function() {
var event = new CustomEvent("moveRight", {
"detail": "Example of an event"
});
document.dispatchEvent(event)
var event1 = new CustomEvent("stopRight", {
"detail": r
});
document.dispatchEvent(event1);
}, 300);
};
}
moves = [];
}
function myMove4(pos) {
var elem = document.getElementById("square");
var id = setInterval(frame, 5);
var i = elem.style.left == '' ? 0 : parseInt(elem.style.left.replace('px', ''));
pos = elem.style.left == '' ? pos : pos + i;
console.log(i + ' ' + pos);
function frame() {
if (elem.style.left == pos + 'px') {
clearInterval(id);
} else {
// pos++;
elem.style.left = (i++) + "px";
}
}
}
#square {
width: 50px;
height: 50px;
background-color: blue;
position: relative;
animation: myfirst 5s linear 2s infinite alternate;
}
<input type='button' value='up' onclick='up()'></input>
<input type='button' value='down' onclick='down()'></input>
<input type='button' value='left' onclick='left()'></input>
<input type='button' value='right' onclick='right()'></input>
<input type='button' value='Run' onclick='Run()'></input>
<div id="square"></div>
<!--https://jsfiddle.net/0rxs9jpy-->
What I am looking for is if I press the right button twice and then Run it does two movements and then stops.
One way to do this was to use javascript Promises
Working example is below:
<html>
<head></head>
<body>
<input type = 'button' value = 'up' onclick = 'up()'></input>
<input type = 'button' value = 'down' onclick = 'down()'></input>
<input type = 'button' value = 'left' onclick = 'left()'></input>
<input type = 'button' value = 'right' onclick = 'right()'></input>
<input type = 'button' value = 'Run' onclick = 'Run()'></input>
<br />
<br />
<br />
<div id = "square"></div>
<script>
var moves = [];
leftpx = 0;
downpx = 0;
uppx = 0;
rightpx = 0;
var up = function() {
moves.push('up')
}
var down = function() {
moves.push('down')
}
var left = function() {
moves.push('left')
}
var right = function() {
moves.push('right')
}
function setTimeoutPromise(ms) {
return new Promise(function(resolve) {
setTimeout(resolve, ms);
});
}
function foo(item, ms) {
return function() {
return setTimeoutPromise(ms).then(function() {
if (item == 'right') {
myMove4(100)
};
if (item == 'down') {
myMove2(100)
};
if (item == 'left') {
myMove3(-100)
};
if (item == 'up') {
myMove(-100)
};
});
};
}
function bar() {
var chain = Promise.resolve();
moves.forEach(function(el, i) {
chain = chain.then(foo(el, 600));
});
return chain;
}
bar().then(function() {});
var Run = function() {
bar();
moves = [];
}
function myMove(pos) {
var elem = document.getElementById("square");
var id = setInterval(frame, 5);
var i = elem.style.top == '' ? 0 : parseInt(elem.style.top.replace('px', ''));
pos = elem.style.top == '' ? pos : pos + i;
console.log(i + ' ' + pos);
function frame() {
if (elem.style.top == pos + 'px') {
clearInterval(id);
} else {
elem.style.top = (i--) + "px";
}
}
}
function myMove2(pos) {
var elem = document.getElementById("square");
var id = setInterval(frame, 5);
var i = elem.style.top == '' ? 0 : parseInt(elem.style.top.replace('px', ''));
pos = elem.style.top == '' ? pos : pos + i;
console.log(i + ' ' + pos);
function frame() {
if (elem.style.top == pos + 'px') {
clearInterval(id);
} else {
// pos++;
elem.style.top = (i++) + "px";
}
}
}
function myMove3(pos) {
var elem = document.getElementById("square");
var id = setInterval(frame, 5);
var i = elem.style.left == '' ? 0 : parseInt(elem.style.left.replace('px', ''));
pos = elem.style.left == '' ? pos : pos + i;
console.log(i + ' ' + pos);
function frame() {
if (elem.style.left == pos + 'px') {
clearInterval(id);
} else {
// pos++;
elem.style.left = (i--) + "px";
}
}
}
function myMove4(pos) {
var elem = document.getElementById("square");
var id = setInterval(frame, 5);
var i = elem.style.left == '' ? 0 : parseInt(elem.style.left.replace('px', ''));
pos = elem.style.left == '' ? pos : pos + i;
console.log(i + ' ' + pos);
function frame() {
if (elem.style.left == pos + 'px') {
clearInterval(id);
} else {
// pos++;
elem.style.left = (i++) + "px";
}
}
}
</script>
<style>
#square{
width: 50px;
height: 50px;
background-color: blue;
position: relative;
animation: myfirst 5s linear 2s infinite alternate;
}
</style>
</body>
</html>
jQuery.noConflict();
(function($) {
$(function() {
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
function startTimer() {
var dataStartElem = jQuery(this);
var dataStart = dataStartElem.attr('data-start');
if (dataStart == 'false') {
dataStartElem.attr('data-start', 'true');
var nextElem = dataStartElem.parent('td').next('.count');
var duration = dataStartElem.attr('data-value');
var a = duration.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
setInterval(function() {
seconds--;
if (seconds >= 0) {
nextElem.html(toTimeString(seconds));
dataStartElem.attr('data-start', 'false');
}
if (seconds === 0) {
alert('time out');
clearInterval(seconds);
}
}, 1000);
}
}
jQuery('.timer').on('click', startTimer);
$('table').stacktable();
});
})(jQuery);
fiddle demo https://jsfiddle.net/arra6j6h/6/
javascript timer in the table does not work and time does not appear when responsive, but all normal when not responsive
I have a thumb scroller on my site and the problem is, when thumbs reach end scroller leaves blank spaces before it goes back to beginning... Can anyone help how to achive this... Thank you in advance!
This is the url: http://marinmartinovic.com/MK_test/
It could take a little bit to load. Still need to optimize images...
This is js:
$(document).ready(function(event) {
/*
*
* SORTING INDEX NUMBERS
*
*/
function sortIndexNumbers(){
loadPhotoIndex = 0;
indexNumbers = [];
for(var i = 0; i<photosLength;i++){
indexNumbers.push(i);
}
if(photoIndex === 0){
indexNumbersToAdd = indexNumbers.splice(photosLength-1, 1);
indexNumbers = indexNumbersToAdd.concat(indexNumbers);
}
if(photoIndex > 1){
indexNumbersToAdd = indexNumbers.splice(0, photoIndex -1);
indexNumbers = indexNumbers.concat(indexNumbersToAdd);
}
loadPhoto();
}
/*
*
* LOAD THUMBS
*
*/
var aThumbsWidth = [];
var speedThumb = 750;
var thumbIndex = 0;
var thumbSwiped = 0;
var thumbsWidth = 0;
function loadThumb(){
$('<img src="'+ aThumbs[thumbIndex] +'">').one('load', function() {
$(".thumb-content ul").append('<li><div class="thumb" id="thumb" data-index=' + thumbIndex + '><img src="'+ aThumbs[thumbIndex] +'"></div></li>');
//setTimeout(function() {
aThumbsWidth.push($('.thumb-content .thumb img').get(thumbIndex).width);
thumbsWidth+= $('.thumb-content .thumb img').get(thumbIndex).width + thumbSpacing;
thumbIndex++;
if(thumbIndex < aThumbs.length){
loadThumb();
}
// all 3 loaded
if(thumbIndex === aThumbs.length){
highlightThumb();
// find thumb and get its position
console.log(photoIndex);
var thumbPosition = $('.thumb-content').find("[data-index='" + photoIndex + "']").position().left;
selectThumb(thumbPosition);
}
//}, 50);
}).each(function() {
//if(this.complete) $(this).load();
});
}
/*
*
* SWIPE THUMB SLIDER
*
*/
var currentThumb = 0;
var currentThumbShift = 0;
$(".thumb-content").swipe( {
tap:function(event, target) {
if(!loadingInProgress){
photoIndex = parseFloat(target.getAttribute('data-index'));
selectPhoto();
highlightThumb();
}
},
triggerOnTouchEnd: false,
swipeStatus: swipeThumbStatus,
allowPageScroll: "vertical",
threshold: 200
});
function swipeThumbStatus(event, phase, direction, distance, fingers)
{
thumbSwiped = distance;
/*if( phase === "move" && (direction === "left" || direction === "right") )
{
var duration = 0;
if (direction === "left"){
scrollThumbs(currentThumbShift + distance, duration);
}
else if (direction === "right"){
scrollThumbs(currentThumbShift - distance, duration);
}
}
else if ( phase === "cancel")
{
scrollThumbs(currentThumbShift, duration);
}*/
if ( phase === "end" ){
if (direction === "right"){
if(!loadingInProgress){
prevPhoto();
setThreePhotos(prevPhoto, 1500, 1);
}
}
else if (direction === "left"){
if(!loadingInProgress){
nextPhoto();
setThreePhotos(nextPhoto, 1500, 1);
}
}
}
}
function selectThumb(distance){
currentThumb = currentThumb + photoIndex;
TweenLite.to($(".thumb-content"), 0.75, {left: -distance, ease:Power4.easeOut, force3D:true});
}
$('body').on('click', '.thumb', function(e) {
if(!loadingInProgress){
photoIndex = parseFloat($(this).attr('data-index'));
selectPhoto();
highlightThumb();
selectThumb($(this).position().left);
}
});
function highlightThumb(){
$('.thumb').css('opacity', '1');
$('.thumb-content').find("[data-index='" + photoIndex + "']").css('opacity', '0.5');
}
/*
*
* NEXT PREVIOUS THUMB
*
*/
var arrow = false;
var nextThree ;
var intervalBuffer;
$('#next-thumb').click(function(event) {
if(!loadingInProgress){
photoIndex += 2;
if((photoIndex+1) >= aPhotos.length){
photoIndex = 0;
}
selectPhoto();
highlightThumb();
// find thumb and get its position
var thumbPosition = $('.thumb-content').find("[data-index='" + photoIndex + "']").position().left;
selectThumb(thumbPosition);
}
});
$('#prev-thumb').click(function(event) {
if(!loadingInProgress){
photoIndex -= 2;
if((photoIndex+1) < 0){
photoIndex = aPhotos.length-1;
}
selectPhoto();
highlightThumb();
// find thumb and get its position
var thumbPosition = $('.thumb-content').find("[data-index='" + photoIndex + "']").position().left;
selectThumb(thumbPosition);
}
});
function setThreePhotos(callback, delay, repetitions) {
clearInterval(threePhotos);
var x = 0;
var threePhotos = setInterval(function () {
callback();
if (++x === repetitions) {
clearInterval(threePhotos);
}
}, delay);
}