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.
Related
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.
It's a follow up to this question - https://stackoverflow.com/a/33430608/3766930
Basically I have a text area and when user starts typing in sth, the counter starts going down from 3 to 0. when it reaches 0 it gets disabled.
Now I want to add a feature of starting over - when user clicks the link start over, text area goes enabled again and user has 3 seconds (again) to perform the input.
I modified the jquery script:
$('#textArea').on('input propertychange', display30Seconds);
var interval;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
}
}, 1000);
}
but I see that I cannot call the method display30Seconds(); again. Or rather I can, but the interval is not set again. How can I fix it?
Seems like I'm not entering the code inside
if (!interval)
because the interval is not visible any more after clearing it (?). So I thought about moving the var interval; into the body of the method function display30Seconds() {, but that doesn't bring the expected effect. Is there a way of fixing it?
Here is my updated fiddle: http://jsfiddle.net/jf4ea4nx/3/
Set interval=null after the clearInterval() call.
What seems to confuse you is the semantics of clearInterval(interval). As Patrick Evans points out in his comment, it will not set interval to a value that evaluates to false in a condition.
To make it completely clear you could use a boolean variable such as countdownRunning in addition to the interval variable to keep track of whether the countdown is active or not.
Try this:
$('#textArea').on('input propertychange', display30Seconds);
var interval=false;
function display30Seconds() {
var validTime = 3000;
if (!interval)
interval = setInterval(function () {
$('#counter').html(validTime / 1000);
validTime = validTime - 1000;
if (validTime < 0) {
clearInterval(interval);
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$(document).on('click','#counterIsDone', function(){
$('#textArea').prop('disabled', false);
display30Seconds();
});
interval=false;
}
}, 1000);
}
You can improve your code by using a conditional recursive call to to your iterative function instead - each call has a one second delay, which makes it slightly more intuitive to use (think of each call as one tick):
var seconds = 3;
$('#textArea').on('input propertychange', setTimeout(timeout.bind(null, seconds), 1000));
function timeout (iterations) {
$('#counter').html(iterations);
if (iterations === 0) {
alert('Time Up!');
$('#textArea').prop('disabled', true);
$('#counter').html('start over');
$('#counterIsDone').on('click', function(){
$('#textArea').prop('disabled', false);
timeout(seconds);
});
}
else {
setTimeout(timeout.bind(null, --iterations), 1000);
}
}
The bind function simply binds the arguments of the bind function to the arguments of the timeout call - the first argument to the bind function declares its this scope; but don't worry about that too much.
You can modify the duration of the timer by changing the seconds var. Hope this helps :)
I have a click event that has a Jquery animation in it.
How can i guarantee that the animation has finished when multiple click events are being fired.
$(this._ScrollBarTrack).click(function(e) {
if(e.target === this && _self._horizontalClickScrollingFlag === false){
_self._horizontalClickScrollingFlag = true;
if(_self._isVertical){
} else{ //horizontal
if(e.offsetX > (this.firstChild.offsetWidth + this.firstChild.offsetLeft)){ // Moving Towards Right
var scrollableAmountToMove = _self._arrayOfCellSizes[_self._scrollBarCurrentStep + 1]; // additional amount to move
var scrollableCurrentPosition = -($(_self._bodyScrollable).position().left);
var scrollBarCurrentPosition = $(_self._ScrollBarTrackPiece).position().left;
var scrollBarAmountToMove = _self.getScrollBarTrackPiecePositionBasedOnScrollablePosition(scrollableAmountToMove);
$(".event-scroll-horizontally").animate({left:-(scrollableCurrentPosition+ scrollableAmountToMove)});
$(_self._ScrollBarTrackPiece).animate({left: (scrollBarCurrentPosition + scrollBarAmountToMove)});
_self._scrollBarCurrentStep += 1;
} else{
var scrollableAmountToMove = _self._arrayOfCellSizes[_self._scrollBarCurrentStep - 1]; // additional amount to move
var scrollableCurrentPosition = -($(_self._bodyScrollable).position().left);
var scrollBarCurrentPosition = $(_self._ScrollBarTrackPiece).position().left;
var scrollBarAmountToMove = _self.getScrollBarTrackPiecePositionBasedOnScrollablePosition(scrollableAmountToMove);
$(".event-scroll-horizontally").animate({left:-(scrollableCurrentPosition - scrollableAmountToMove)});
$(_self._ScrollBarTrackPiece).animate({left: (scrollBarCurrentPosition - scrollBarAmountToMove)});
_self._scrollBarCurrentStep -= 1;
}
}
_self._horizontalClickScrollingFlag = false;
}
});
jQuery has a hidden (I'm not sure why it's not in the docs someplace) variable $.timers that you can test against.
I made this function a long time ago to handle situations like this. Mind you, this will test to make sure there are NO animations currently being executed.
function animationsTest (callback) {
var testAnimationInterval = setInterval(function () {
if ($.timers.length === 0) { // any page animations finished
clearInterval(testAnimationInterval);
callback(); // callback function
}
}, 25);
};
Useage: jsFiddle DEMO
animationsTest(function () {
/* your code here will run when no animations are occuring */
});
If you want to test against one individually you could do a class/data route.
$('#thing').addClass('animating').animate({ left: '+=100px' }, function () {
// your callback when the animation is finished
$(this).removeClass('animating');
});
You could declare a global boolean called isAnimating and set it to true right when you begin the animation. Then add a done or complete function to the animation that sets it back to false. Then set your click event to only begin the animation if isAnimating is false.
I am facing one problem in JS, please help me to resolve this.. I have two methods they are simultaneously executing one after other.. I have to stop them after second click on image.
Below is my JS code
I am calling fadeIn(img1, img2, img3) after first click on image then some animation will be goes on, once I click second time the whole animation(method execution) should be stopped.
var t1 = 0;
var t2 = 0;
function fadeIn(img1, img2, img3) {
$(imgIdForClick_1).addClass('animated pulse');
$('#cashBar1').addClass('animated pulse');
$('#cashBarDec1').addClass('animated pulse');
var t1 = setTimeout(function() {
fadeOut(img1, img2, img3);
if (clickCount_1 >= 2) {
alert("clicked 1");
return false;
}
}, 500);
//t1 = setTimeout(fadeOut, 500);
};
function fadeOut(img11, img22, img33) {
$(imgIdForClick_1).removeClass('animated pulse');
$('#cashBar1').removeClass('animated pulse');
$('#cashBarDec1').removeClass('animated pulse');
var t2 = setTimeout(function() {
fadeIn(img11, img22, img33);
if (clickCount_1 >= 2) {
alert("clicked 2");
return false;
}
}, 500);
//t2 = setTimeout(fadeIn, 500);
};
By below code I am calling this snippet in first click
imgId1 = $('#img1');
imgId2 = $('#cashBar1');
imgId3 = $('#cashBarDec1');
fadeIn(imgId1, imgId2, imgId3);
After second click
clickCount_1 varibale will be 2
clearTimeout(t1);
clearTimeout(t2);
See the DEMO. Click on the image to stop animation.
I have added a flag that would be checked upon the call of the function, and if the value is true then and then only the functions would be called. The flag would be set to false when clicked on image, so the function would be called no longer.
code:
var animate = true;
function fadeIn() {
$('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
if(animate == true)
{
setTimeout(fadeOut,1000);
}
};
function fadeOut() {
$('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
if(animate == true)
{
setTimeout(fadeIn,1000);
}
};
fadeIn();
$('#image').click(function(){
animate = false;
alert('now the animation will stop');
});
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);
}