Tryin to do two things in a Loop in Javascript - javascript

I wrote a script in Javascript with 2 functions.
Die first shows random pictures in an random position
This works fine
The second script has to "clear up" everthing and put everything back to the Startposition.
My script at this time:
function clearPics(){
$("img[class^='mapic']").attr('src','empty100.jpg');
$("img[class^='mapic']").attr("title",'');
$("img[class^='mapic']").attr("alt",'');
}
function makePics(){
// 1 Step take 5 different Pics
var MAAuswahlArr = [];
var AnzahlAnzeige = 5;
var lauf = AnzahlAnzeige
while (lauf > 0){
var testvar = getRandomInt(0,MAArr.length-1);
if (contains.call(MAAuswahlArr, testvar)){
}else{
MAAuswahlArr.push(testvar);
lauf--;
}
}
// 2 Step get 5 of 10 different positions
var BildanzahlMax = 10
var BildanzahlArr = [];
var BildPositionenbesetzt = 5;
lauf = BildPositionenbesetzt;
while (lauf > 0){
var testvar = getRandomInt(0,BildanzahlMax);
if (contains.call(BildanzahlArr, testvar)){
}else{
BildanzahlArr.push(testvar);
lauf--;
}
}
// 3 step: take 5 Pics an put ist in the src the alt and title Tags
lauf = BildanzahlMax;
while (lauf > 0){
var className = "mapic"+lauf;
if (contains.call(BildanzahlArr, lauf)){
$('.'+className).attr('src',MAArr[lauf-1][2]);
$('.'+className).attr("title",MAArr[lauf-1][1]);
$('.'+className).attr("alt",MAArr[lauf-1][0]);
}
lauf--;
}
// 4. step: make the Pics Hover
$("img[class^='mapic']").hover(function() {
var maName = $(this).attr("title");
var mafunktion = $(this).attr("alt");
$('.matextblock').html("<h3> Unser Team</h3> <p class='maName'>"+mafunktion+"</p><p class='maFunktion'>"+maName+"</p>");
console.log('huhu rein');
}, function() {
$('.matextblock').html('');
});
return true;
}
$(document).ready(function() {
setInterval(function(){
var done = makePics();
console.log(done);
if (done){
clearPics();
//console.log('clear');
}else{
done = false;
}
},2000);
});
How can I run the script to
a) make the Picture
b) wait 5 or n seconds
c) clear up
and go back to a) ?

Your done variable should be declared outside of the anonymous function executed by setInterval. Right now it is redeclared every time the function fires, so the if/else branch is useless.
Exampel code:
$(function() {
var pictureShown = false;
var interval = 5000;
setInterval(function () {
if(pictureShown) {
clearPics();
} else {
makePics();
pictureShown = true;
//OR, if makePics returns true:
//pictureShown = makePics();
}
}, interval);
});
Edit: I adapted your setInterval code to make it work, but the whole setup could be much simplified - see Adder's response.

Thank Folks I got it
this is my Code witch workls fine for me.
Ich change the positio for the clearPics funtion.
So I do not have to wait 5 Seconds to the next Pictures :-?
var done = false;
var interval = 5000;
$(document).ready(function() {
setInterval(function(){
//done = makePics();
if (done){
done = false;
}else{
clearPics();
done = makePics();
}
console.log(done);
},interval);
});

I think the code can be simplified. As far as I can tell from the info on the functions you gave out.
$(document).ready(function() {
makePics();
setInterval(function(){
clearPics();
var done = makePics();
},2000);
}
This will clear the pics first, and then redisplay a new set of Pics with makePics, every 2000 ms.

Related

Freezing site elements until time pass

After clicking "Take a break" number of sets should decrement, and clock should start.
During clock working, clicking on any element of site should be cousing any effect.
Instead, the first click and it works properly, but after first clock pass, i can click decrement sets during the clock work and click another breaks.
I want to do this without asynchronous stuff (project's requirement ;/ )
I tried adding a freezing variable but i have problem how properly place the ifs.
Here is fragment which i struggle with:
var freeze = false
$(".start").click(function(){
if(!freeze){
freeze = true;
var num = $(this).attr("id");
var currExcercise = routineSample.excercises[num];
var res = this;
var timer = 0;
var setsTd = "#set"+num;
if(!currExcercise.allSetsDone)
{
timer = currExcercise.breakTime;
currExcercise.sets--;
if(currExcercise.sets <= 0 ){
currExcercise.sets = 0;
currExcercise.allSetsDone = true;
}
$(setsTd).text(currExcercise.sets);
if(!currExcercise.breakPassed){
setInterval(function(){
if(timer>0){
timer--;
$(res).text(timer);
}else{
if(!freeze)
$(res).text("MOVE ON!");
currExcercise.timeLeft = timer;
freeze = false;
//currExcercise.breakPassed = true;
}
}, 1000);
freeze = true;
}
}else{
$(res).text("EXCERCISE DONE");
}
} });
To "freeze" a page use the following CSS:
body { pointer-events: none };

Button to start/stop an infinite loop through functions with delay between each

I'm trying to create a function that on the click of a button will start a loop through each function with a 5 second delay between each and loop infinitely until the button is clicked again. I'm close with this, but after 5 seconds, it only just executes the last function in the set (tuesday) and does not iterate through them with a delay between each.
function links() {
safety
daily
monday
tuesday
}
var intervalId;
function toggleIntervalb() {
if (!intervalId) {
intervalId = setTimeout(links, 5000);
} else {
clearInterval(intervalId);
intervalId = null;
}
}
function safety(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'block';
document.getElementById("daily").style.display = 'none';
document.getElementById("monday").style.display = 'none';
document.getElementById("tuesday").style.display = 'none';
}
function daily(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'none';
document.getElementById("daily").style.display = 'block';
document.getElementById("monday").style.display = 'none';
document.getElementById("tuesday").style.display = 'none';
}
function monday(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'none';
document.getElementById("daily").style.display = 'none';
document.getElementById("monday").style.display = 'block';
document.getElementById("tuesday").style.display = 'none';
function tuesday(){
document.getElementById("fires").style.display = 'none';
document.getElementById("safety").style.display = 'none';
document.getElementById("daily").style.display = 'none';
document.getElementById("monday").style.display = 'none';
document.getElementById("tuesday").style.display = 'block';
**2nd Attempt:
Closer with this (includes button)
New to jsfiddle - can't make my code work here: https://jsfiddle.net/unqrhxtp/16
So, I am also including the pastebin (save as .html and open): https://pastebin.com/EwHVqmHJ
Currently, the code stops after executing the first function. It appears to loop on the first element only (if you click another link manually, it forces back to the first function in the set).
Thanks in advance.
Changing this line:
intervalId = setTimeout(links, 5000);
from a setTimeout to a setInterval will probably fix that
intervalId = setInterval(links, 5000);
Update
After reading your updated question I think something like this will solve your problem:
// Gather functions in an array, easier to loop trough
var links = [
safety,
daily,
monday,
tuesday,
wednesday,
thursday
]
function cyclelinks() {
links.forEach(function(link, index) {
var delay = index * 5000;
var fn = links[index];
setTimeout(fn, delay)
});
}
var intervalId;
function toggleInterval() {
var btn = document.getElementById("logo");
if (!intervalId) {
var delay = links.length * 5000; // repeat after all functions are called with 5 sec delay
cyclelinks()
intervalId = setInterval(cyclelinks, delay);
} else {
clearInterval(intervalId);
intervalId = null;
location.reload();
}
}
You should use setInterval because setTimeout runs after gived time means it works correctly because. If you run this code step by step then you can see what i am saying. When cursor on the settimeout your functions doesnt work immediately it will wait 5 secs.
I hope i could help
I managed to come up with a solution, although I'm not totally happy with it. Mostly because it forces me to wait a full 90 seconds before the looping starts. For now, this will do, but I'll leave this open in hopes someone will post a better solution.
//Loop through links upon click
function cyclelinks() {
setTimeout(safety, 10000);
setTimeout(daily, 20000);
setTimeout(monday, 30000);
setTimeout(tuesday, 40000);
setTimeout(wednesday, 50000);
setTimeout(thursday, 60000);
}
var intervalId;
function toggleInterval() {
var btn = document.getElementById("logo");
if (!intervalId) {
intervalId = setInterval(cyclelinks, 90000);
} else {
clearInterval(intervalId);
intervalId = null;
location.reload();
}
}

Javascript setTimeout for an array

The concept is to create a lift operation. Upon clicking 1, the display should show 1 and similarly for other floors.
I have done the code.
if i click on 2, 3 ,4 consecutively 2nd floor is having a delay of 10000ms which is set in setTimeOut but 3&4 are executing immediately.
Here is my JSFIDDLE.
Could someone help me out to get equal intervals on 4 floors.
var liftArray = [];
var liftCurrentPosition = 1;
$(document).ready(function(){
$("#currentPosHTML").text(liftCurrentPosition);
});
$(".floorbuttons").click(function(){
$(this).attr("disabled", true);
var selectedfloor = parseInt($(this).text());
console.log(selectedfloor);
if(liftArray == 0 || selectedfloor!=liftArray[liftArray.length-1]){
liftArray.push(selectedfloor);
setInterval(function(){
movelift(liftArray[0]);
liftArray.splice(0,1);
},10000);
}
});
function movelift(value){
$("#currentPosHTML").text(value);
liftCurrentPosition = value;
$(".floorbuttons").each(function(){
if($(this).text() == liftCurrentPosition){
$(this).attr("disabled",false);
}
});
};
Using setInterval is correct, but you have to make sure you only start it if the elevator is currently not working. If it's working, it will trigger every 5 seconds, and when it has reached all floors, the interval needs to be cancelled.
So add this as a general variable:
var refreshIntervalId;
Change the click function to:
$(".floorbuttons").click(function(){
$(this).attr("disabled", true);
var selectedfloor = parseInt($(this).text());
console.log(selectedfloor);
if (liftArray == 0) {
refreshIntervalId = setInterval(function () {
movelift();
}, 10000);
}
if(liftArray == 0 || selectedfloor!=liftArray[liftArray.length-1]){
liftArray.push(selectedfloor);
}
});
And lastly change the movelift function:
function movelift(){
var value = liftArray.shift();
if (!value) {
clearInterval(refreshIntervalId);
return;
}
$("#currentPosHTML").text(value);
liftCurrentPosition = value;
$(".floorbuttons").each(function(){
if($(this).text() == liftCurrentPosition){
$(this).attr("disabled",false);
}
});
};
Fiddle
Use the setTimeout method inside the movelift function.

jQuery setInterval too fast when tab is inactive

When the tab my website is on is inactive, my slideshow starts switching pictures too fast and mess the whole thing up.
Is there a way i could fix this?
var img_src = ["1.png", "2.png", "3.png", "4.png"];
var delay = 8000;
var first_run = true;
function switch_pic(position){
$("#show").attr("src", img_src[position]).fadeOut(0).fadeIn(4000).fadeOut(4000);
}
$(document).ready(function(){
var i = 0;
if(first_run){
switch_pic(i);
first_run = false;
i++;
}
window.setInterval(function(){
switch_pic(i);
delay += 8000;
i++;
if(i > 3){
i = 0;
window.clearInterval();
}
}, delay);
});
Could wrap the code in this:
$(document).ready(function(){
$([window, document]).focusin(function(){
//code run when tab is selected
}).focusin(function(){
//code to stop all animation
});
});
That would only let the slideshow run when the user is viewing your site.
I'm not sure why things speed up. Normally the timers on background tabs will be slowed down to at least one second, but this shouldn't affect your scenario. I suggest using console.log() to track the calls to your functions.
Also, you can simplify your main loop a bit:
$(document).ready(function(){
var i = 0;
window.setInterval(function(){
switch_pic(i++); // increase i after call
if(i > 3) i = 0; // reset i
}, 8000);
});
I think that the answer good for actual version of jQuery should look like this:
var intervalId;
$([window, document]).on('focusin', function(){
intervalId = setInterval(function() {
// Action in interval
}, 3000);
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
}
});
Pleas remember, that first time your 'focusin' is not tigger when page is loaded, so you should use this construction for this:
intervalFunction();
$([window, document]).on('focusin', function(){
if (!intervalId){
intervalFunction();
}
}).on('focusout', function(){
if (intervalId) {
clearInterval(intervalId);
intervalId = undefined;
}
});
function intervalFunction() {
// Your function hire
}

Hide download link for 10 seconds? js

hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}

Categories

Resources