Я пытаюсь использовать счетчик в моей полной функции, чтобы убедиться, что анимация margin-top завершена, прежде чем двигаться дальше. Прямо сейчас, у меня есть счетчик в моей MakeList(), и в моей функции Spin() я console.log счетчик, и он не распознает счетчик ++, потому что он срабатывает до окончания анимации. Никто, я спрашиваю, не может понять, почему.Полная функция, не заставляющая jquery ждать окончания анимации
** Примечание: я не могу использовать timeOut, потому что время установлено на случайное (предполагается, что оно выглядит как игровой автомат ** Кроме того, я не могу найти то, что говорит эта тестовая платформа, является ошибкой, но код работает на моей машине. на самом деле скрипт-2.js все мне нужно показать, чтобы получить точку зрения, хотя :)
// ********************************************************
// SLOT MACHINE ICONS. Each array has 3 icons for each slot
// ********************************************************
var array1 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array2 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
var array3 = [
'<div data-id="0" style="width:100%; background:#fff; height:150px;"></div>',
'<div data-id="1" style="width:100%; background:#ccc; height:150px;"></div>',
'<div data-id="0" style="width:100%; background:#666; height:150px;"></div>'
]
// Generates random # between 0 and 2. Used for choosing winner and creating random slots
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generates winning array item between coffee, tea and espresso
function win(whatArray){
\t var arrayItem = getRandomInt(0,2);
var winItem = whatArray[arrayItem];
return winItem;
}
// Populates each slot with random icons to spin through
var makeList = function(whatArray, whatSlot){
\t var slotArray = [];
\t for(i=0; i < 100; i++){
var randNum = getRandomInt(0,2); // Generate random number
var findItem = whatArray[randNum]; // Use random number to find associated array item
var slot = whatSlot; // Set which slot to append array item to (first, second or third)
$('#' + slot).append('<div>'+findItem+'</div>'); // Append icon to HTML
}
var winItem = win(whatArray); // Generate winning icon for slot
console.log("winner " + winItem);
$('#' + slot).append('<div>'+winItem+'</div>'); // Append winning icon to end of list
}
// Spin the slot and win some caffeine!
function Spin(){
\t window.counter = 0;
\t // Generate lists for each slot
\t makeList(array1, 'slot-1');
\t makeList(array2, 'slot-2');
\t makeList(array3, 'slot-3');
\t MoveSlots($('#slot1-wrapper'), 2500);
\t MoveSlots($('#slot2-wrapper'), 5200);
\t MoveSlots($('#slot3-wrapper'), 500);
\t //var running = true;
\t // console.log(running);
\t var slot1attr = $('#slot1-wrapper div').children().last().attr('data-id');
\t var slot2attr = $('#slot2-wrapper div').children().last().attr('data-id');
\t var slot3attr = $('#slot3-wrapper div').children().last().attr('data-id');
\t
\t \t console.log('counter = ' + counter);
\t \t if(counter > 0){
\t \t \t if(slot1attr == slot2attr && slot1attr == slot3attr){
\t \t \t \t console.log("WIN");
\t \t \t } else {
\t \t \t \t console.log("LOSE");
\t \t \t }
\t \t }
\t function MoveSlots(el, speed){
\t \t var time = speed;
\t \t time += Math.round(Math.random()*10000);
\t \t el.stop(true,true);
\t \t var marginTop = -(100 * 150); //change 100 to height placeholder
\t \t var running = true;
\t \t el.animate({
\t \t \t 'margin-top':'+='+marginTop+'px'
\t \t }, {
\t \t \t 'duration' : time,
\t \t \t 'easing' : 'easeInOutQuint',
\t \t \t complete: function(){
\t \t \t \t console.log('yolo');
\t \t \t \t //$(this).on('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(){
\t \t \t \t \t counter++;
\t \t \t \t \t console.log(counter);
\t \t \t \t //})
\t \t \t } \t
\t \t });
\t } // end MoveSlots
} // end Spin
body{
/*background-color:white;*/
padding:50px;
margin:50px;
background: #505f77 !important;
}
#slotWrapper {
width:410px;
height:150px;
margin:50px auto;
overflow: hidden;
position:relative;
border:1px solid #f00;
}
#slot1-wrapper, #slot2-wrapper, #slot3-wrapper {
\t margin-top:0;
\t position: relative;
}
.slot {
width:120px;
height:150px;
margin-right:25px;
text-align:center;
float:left;
position: absolute;
}
#slot-3 {
\t margin-right:0;
}
#slot-1 {
\t top:0;
\t left:0;
}
#slot-2 {
\t top:0;
\t left:145px;
}
#slot-3 {
\t top:0;
\t left:290px;
}
.slot div {
width:120px;
height:150px;
}
.slot div img {
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
\t <meta charset="UTF-8">
\t <title>Document</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<!-- <link rel="stylesheet" type="text/css" href="css/default.css" />
<link rel="stylesheet" type="text/css" href="css/component.css" /> -->
<div style="text-align:center">
<input type="button" value="spin!" onClick="Spin();" style="margin-top:4px;">
</div>
<div id="slotWrapper">
<div id="slot1-wrapper">
<div id="slot-1" class="slot"></div>
</div>
<div id="slot2-wrapper">
<div id="slot-2" class="slot"></div>
</div>
<div id="slot3-wrapper">
<div id="slot-3" class="slot"></div>
</div>
</div>
</body>
</html>
Полная функция работает, проблема это выполняется асинхронно –
Это удивительно! Спасибо! У вас есть хорошая ссылка на статью или видео о том, что делает .promise()? Я искал это и не нашел ничего, что мог понять, чтобы помочь связать это ... (или краткое описание для манекена) Еще раз спасибо! @ArunPJohny – user1607991
http://api.jquery.com/jQuery.when/ –