integrating SetTimeOut function after button click - javascript

I have created a snippet of code that changes the state from display:block to display:none by using an onClick element. My goal is to delay the change in state, for a few seconds whilst an animation effect occurs.
This snippet of code below is what I am currently using to change the state of the element, but unsure on how to incorporate a delay.
Any advice or suggestions is greatly appreciated.
Thanks,
Ant
function showDiv1(elem) {
var divsToCheck = ["close","Holder"]; // Add to here to check more divs
for (var i = 0; i < divsToCheck.length; i++) {
if (divsToCheck[i] == elem) {
document.getElementById(divsToCheck[i]).style.display = "block";
} else {
document.getElementById(divsToCheck[i]).style.display = "none";
}
}
}

Put the code you want to be delayed inside an anonymous function, like so:
function showDiv1(elem) {
var divsToCheck = ["close","Holder"]; // Add to here to check more divs
for (var i = 0; i < divsToCheck.length; i++) {
if (divsToCheck[i] == elem) {
setTimeout(function() {
document.getElementById(divsToCheck[i]).style.display = "block";
}, 500);
} else {
setTimeout(function() {
document.getElementById(divsToCheck[i]).style.display = "none";
}, 500);
}
}
}
Here, 500 means delaying by 500 ms. You can change this to whatever amount of time (in milliseconds) that you need.

You should call a function in your loop that takes care of the setTimeout and hiding/showing instead of calling the timeout function in a loop. (Won't work because i is no longer available). See here: https://jsbin.com/refodobaca/1/edit?html,css,js,output
function showDiv1(elem) {
var divsToCheck = ["close","Holder"]; // Add to here to check more divs
for (var i = 0; i < divsToCheck.length; i++) {
if (divsToCheck[i] == elem) {
showHideDiv(divsToCheck[i], true);
} else {
showHideDiv(divsToCheck[i], false);
}
}
}
function showHideDiv(elem, bShow) {
var timeoutSeconds = 3;
setTimeout(function() {
document.getElementById(elem).style.display = (bShow ? "block" : "none");
}, timeoutSeconds * 1000);
}
showDiv1('Holder');

Your question is a little unclear because the name of your function is showDiv1 but you explain that you're trying to hide an element, so I've tried to answer in light of this and hopefully it will give you some ideas.
This code displays a couple of divs. If you click on them they turn red and, after a couple of seconds (to represent an animation), they are hidden.
dummyAnim returns a promise. After the animation has run its course (here represented by a two second delay) it is resolved. I've used await to pause code execution in an async function until the animation has resolved.
// Grab the elements and add click handlers to them
const divs = document.querySelectorAll('div');
divs.forEach(div => div.addEventListener('click', hideElement, false));
function dummyAnim() {
// return a promise which resolves (an animation)
// after two seconds
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), 2000);
});
}
async function hideElement() {
this.classList.add('red');
await dummyAnim();
this.classList.add('hidden');
}
div { color: black; display: block }
.hidden { display: none }
.red { color: red }
<div>close</div>
<div>holder</div>

Related

Is this a Javascript blocking / async scenario?

The user clicks the map and it calls clickMap, the DIV#calculating is displayed, the map calcs are done and then in updateResults the DIV#calculating is hidden.
However the DIV is never shown on screen.
The console log shows
block 9775.199999996403
none 10517.899999998917
The delay between show and hide maybe from 100ms up to 5000ms, no matter what I never see the DIV.
function clickMap(e) {
if (myAStar.nodesPosition[e.offsetY][e.offsetX]) {
document.getElementById("calculating").style.display = "block";
console.log(document.getElementById("calculating").style.display, performance.now());
myAStar = new AStarPathFinder(mapW, mapH);
path = [];
myAStar.setStart(0, 0);
myAStar.setDestination(e.offsetX, e.offsetY);
myAStar.wh = document.getElementById('hWeight').value;
myAStar.loadMap(map);
findPath();
drawMap();
updateResults();
} else {
mapCanvas.classList.add("oops");
setTimeout(() => {
mapCanvas.classList.remove("oops");
}, 500);
}
}
function updateResults() {
document.getElementById("calculating").style.display = "none";
console.log(document.getElementById("calculating").style.display, performance.now());
}

JS - How to run something when a function has ended

Here is a code that should open and close my site's menu. The menu is divided to divs and each one is timed to enter the screen after the other.
<script type="text/javascript">
var s=0;
function menuOpen() {
if (s==0){
document.getElementById("menu_icon").src = "x.png";
document.getElementById("nav_menu").style.zIndex = "3";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.remove('loading');
}, index * 100);
});
s++;
} else {
document.getElementById("menu_icon").src = "menu_icon.png";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.add('loading');
}, index * 100);
});
s=0;
// how to make this part run after the menu has finished folding?
setTimeout(function(){
document.getElementById("nav_menu").style.zIndex = "1";
}, 1500);
}
}
</script>
The content of the page is at z-index 2. The menu when folded is at 1 and when open at 3.
Is there a way to run the command moving the menu to z-index 1 after the menu has finished folding completely?
Currently what I did was to time the animation (1600ms) and use setTimeout. But this timing will change if I'll add more lines to my menu or if someone is clicking rapidly on the menu icon.
I'm rather new to JS and Jquery so go easy on me (:
Thanks of your help.
Below you can find the code and link to jsfiddle. Unfortunetly jsfiddle blocks the animate method for unknown reason so I don't debug, but even if it code will not work :))) I hope you will cathch the idea. And also some explanation.
Firstly our items are hidden. There are two functions displayMenu and hideMenu, they are similar, but display - run animations from the top invisible, and hide - start hide items from the bottom visible. To prevent mess I use two flags and two classes, first openFlag it is say what animations should be played now. Our hide and display functions are recursive and after they end current animation(hide or show) they check openFlag, and play next hide/show or start another chain of hide/show functions. It is the most difficult to understand part) But important that with it you can click as many times as you want and all would be fine and would be never broken by clicks.
Two classes we use as animation-chain can change behaviour and we need the way to choose items that alredy visible or hidden, so this why after each animation we set only one of this classes and remove another.
Now there is one problem if all animation are ended when we click button we should start new chain of animations, but if chain has been already started we need just to switch openFlag, and when current animation stops, it will change the behaviour. So this is the reason for btnFlag it is 1 if no active chain-animations at this moment.
After the last execution of element of animation-chain it will call callback arg, that you should pass, also at this moment will set btnFlag to 0, that means that animation-chain stopped. The openFlag as you remember changed at moment og click.
function end() {
console.log("here you can set zIndex");
}
var openFlag = 0; //become 1 after we start open elems
var btnFlag = 1;
$(document).ready(function() {
$('.toggleMenu').click(function() {
if (!$('.menuBlocks').hasClass('visible')) {
if (openFlag == 0) {
openFlag = 1;
if (btnFlag) {
var items = $('.invisibleItem');
var amount = items.length;
displayMenu(0, amount, items, end);
}
}
} else {
openFlag = 0;
if (btnFlag) {
var items = $('.visibleItem');
var amount = items.length;
hideMenu(amount - 1, items, end);
}
}
});
});
function displayMenu(i, amount, items, callback) {
if (i < amount && openFlag) {
items[i].animate({
"width": "100px"
}, 1000, function() {
items[i].removeClass('invisibleItem');
items[i].addClass('visibleItem');
displayMenu(i + 1, amount, items);
});
} else if (!openFlag) {
var items = $('.visibleItem');
var amount = items.length;
hideMenu(amount - 1, items, makeToggleVisible);
} else {
btnFlag = 1; //all aniimations ended
callback();
}
}
function hideMenu(i, items, callback) {
if (i < 0 && openFlag) {
items[i].animate({
"width": "0px"
}, 1000, function() {
items[i].removeClass('visibleItem');
items[i].addClass('invisibleItem');
hideMenu(i - 1, amount, items);
});
} else if (!openFlag) {
var items = $('.invisibleItem');
var amount = items.length;
displayMenu(0, amount, items, makeToggleVisible);
} else {
btnFlag = 1; //all animations are ended
callback();
}
}
https://jsfiddle.net/ShinShil/nrtyshv5/4/
Ok fixed it.
I moved everything to jquery. Used animate and promise.
This is what came out at the end. It is a side menu that will open it's li elements one-by-one.
var s=0;
var navMenu = document.getElementById("nav_menu");
var navBtn = document.getElementById("btn");
$(document).ready(function(){
$("button").click(function(){
if (s==0) {
navMenu.style.zIndex = "4";
navBtn.classList.add('close');
$('ul').each(function() {
$(this).children().each(function(i) {
$(this).delay(i * 100).animate({left:0});
});
});
$( "li" ).promise().done(function() {
navMenu.style.zIndex = "4";
});
s++;
}
else {
navBtn.classList.remove('close');
$('ul').each(function() {
$(this).children().each(function(i) {
$(this).delay(i * 100).animate({left:"100%"});
});
});
s=0;
$( "li" ).promise().done(function() {
navMenu.style.zIndex = "1";
});
}
});
});
and with CSS transitions.
var s=0;
function menuOpen() {
if (s==0){
document.getElementById("menu_icon").src = "x.png";
document.getElementById("nav_menu").style.zIndex = "3";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.remove('loading');
}, index * 100);
});
s++;
$("#last").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
document.getElementById("nav_menu").style.zIndex = "3";
});
} else {
document.getElementById("menu_icon").src = "menu_icon.png";
$('.box-wrapper').each(function(index, element) {
setTimeout(function(){
element.classList.add('loading');
}, index * 100);
});
s=0;
$("#last").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){
document.getElementById("nav_menu").style.zIndex = "1";
$("#nav_menu").scrollTop(0);
});
}
}

JQuery transition animation

This program randomly selects two employees from a json-object Employees array, winnerPos is already defined.
For better user experience I programmed these functions to change pictures one by one. The animation stops when the randomly selected person is shown on the screen.
The slideThrough function will be triggered when the start button is pressed.
function slideThrough() {
counter = 0;
start = true;
clearInterval(picInterval);
picInterval = setInterval(function () {
changePicture();
}, 500);
}
function changePicture() {
if (start) {
if (counter > winnerPos) {
setWinner();
start = false;
killInterval();
} else {
var employee = Employees[counter];
winnerPic.fadeOut(200, function () {
this.src = 'img/' + employee.image;
winnerName.html(employee.name);
$(this).fadeIn(300);
});
counter++;
}
}
}
The problem is the animation doesn't work smoothly. At first it works, but not perfect. The second time the transition happens in an irregular way, i.e. different speed and fadeIn/fadeOut differs from picture to picture.
Could anyone help me to fine-tune the transition?
I would avoid using setInterval() and add a function to the call to .fadeIn() that starts the animation of the next picture.
It would look like this:
function changePicture(pos) {
pos = pos || 0;
if (pos <= winnerPos) {
var employee = Employees[pos];
winnerPic.fadeOut(200, function() {
this.src = 'img/' + employee.image;
winnerName.html(employee.name);
$(this).fadeIn(300, function() {
changePicture(pos + 1);
});
});
} else {
setWinner();
}
}
To start the animation, you call changePicture() without any arguments, like this.
changePicture();
jsfiddle

OnMouseOver start loop, OnMouseOut kill loop

I created this little function that loops through images when you go mouse over:
function THUMB_ROLL(NEXT)
{
LENGTH = ALL_IMAGES.length;
if(!LENGTH) { return false; }
if(!NEXT || NEXT === LENGTH) { NEXT = 0 }
$('#IMAGE_THUMB').css('background-image','url(/<?php echo $ITEM_CODE;?>/'+ALL_IMAGES[NEXT]+')');
setTimeout(function()
{
THUMB_ROLL(NEXT+2)
},800);
}
</script>
I have, onmouseover="THUMB_ROLL();"
But, I cannot seem to find a solution to stop the loop once onmouseout. Any help appreciated!
EDIT
<script>
var timer;
function THUMB_ROLL(NEXT)
{
LENGTH = ALL_IMAGES.length;
if(!LENGTH) { return false; }
if(!NEXT || NEXT === LENGTH) { NEXT = 0 }
$('#IMAGE_THUMB').css('background-image','url(/<?php echo $ITEM_CODE;?>/'+ALL_IMAGES[NEXT]+')');
timer = setTimeout(function()
{
THUMB_ROLL(NEXT+1)
},800);
}
$(document).on('mouseover','#IMAGE_THUMB',function()
{
THUMB_ROLL();
});
$(document).on('mouseout','#IMAGE_THUMB',function()
{
clearTimeout(timer);
});
</script>
Assign your timeout to a variable which store the timerID.
Then have the moueout clear the timeout, which should stop the flow.
var timer;
// mouseover event..
timer = setTimeout(function() {
THUMB_ROLL(NEXT+2)
},800);
// mouseout event
clearTimeout(timer);
Also it is a better idea to separate your concerns and attach the events inside the script tags instead of attaching them inline.

restart loop after it's paused by flag

I'm putting together some code to essentially replace the contents of a div when I mouseover a specific link. I then added the changer function to cycle through the content replacement automatically. I set flags for mouseover and mouseout and I can actually get the changer function to stop on mouseover but I can't quite figure out how to make it start up again on mouseout. Any advice is appreciated.
var pause=false;
$('.banner-nav a').mouseover(function () {
pause=true;
setFeature(this);
return false;
});
$('.banner-nav a').mouseout(function () {
pause=false;
});
changer(0, 5000);
function setFeature(f) {
var m = $(f).attr('rel');
$('.banner-nav a').not(f).removeClass('active');
$(f).addClass('active');
$('#featureContainer').html($(m).html());
}
function changer(index, interval) {
var buttons = $('.trigger'),
buttons_length = buttons.length;
var button = buttons.eq(index % buttons_length);
setFeature($(button));
setTimeout(function() {
if (!pause) {
changer(++index, interval);
}
}, interval)
}
The issue is that changer is responsible for its own delayed execution, but pausing it stops the scheduled execution. Another problem is that the next scheduled execution (if any) still happens after pausing.
Use setInterval instead of setTimeout. Instead of using a flag, clear the interval to pause and start it again to unpause.
(function() {
var index=0;
function changer() {
var buttons = $('.trigger'),
buttons_length = buttons.length;
var button = buttons.eq(index % buttons_length);
setFeature($(button));
++index;
}
var changerInterval,
period = 5000;
function startChanger() {
if (! changerInterval) {
changerInterval = setInterval(changer, interval);
}
}
function stopChanger() {
clearInterval(changerInterval);
changerInterval = 0;
}
$('.banner-nav a').mouseover(function () {
stopChanger();
setFeature(this);
return false;
});
$('.banner-nav a').mouseout(function () {
startChanger();
});
/* could implement other functions to e.g. change the period */
function setChangerPeriod() {
...
}
window.setChangerPeriod = setChangerPeriod;
...
})

Categories

Resources