애니메이션이있는 함수가 다른 함수를 실행할 때까지 완료 될 때까지 기다립니다.
나는 그들 각각에 많은 애니메이션 을 포함하는 정상적인 ( non-ajax ) 기능에 문제가 있습니다. 현재 나는 단순히 기능 사이에 있지만 브라우저 / 컴퓨터가 동일하지 않기 때문에 완벽하지 않습니다.setTimeout
추가 참고 사항 : 둘 다 충돌하는 별도의 애니메이션 등이 있습니다.
단순히 다른 하나의 콜백 함수에 넣을 수는 없습니다.
// multiple dom animations / etc
FunctionOne();
// What I -was- doing to wait till running the next function filled
// with animations, etc
setTimeout(function () {
FunctionTwo(); // other dom animations (some triggering on previous ones)
}, 1000);
어쨌든 js / jQuery에 다음이 있습니까?
// Pseudo-code
-do FunctionOne()
-when finished :: run -> FunctionTwo()
$.when()
& $.done()
에 대해 알고 있지만 AJAX 용입니다.
- 내 업데이트 된 솔루션
jQuery에는 $ .timers라는 노출 된 변수 (어떤 이유로 jQuery 문서의 어디에도 나열되지 않음)가 있으며,이 변수는 현재 발생하는 애니메이션 배열을 보유합니다.
function animationsTest (callback) {
// Test if ANY/ALL page animations are currently active
var testAnimationInterval = setInterval(function () {
if (! $.timers.length) { // any page animations finished
clearInterval(testAnimationInterval);
callback();
}
}, 25);
};
기본 사용법 :
// run some function with animations etc
functionWithAnimations();
animationsTest(function () { // <-- this will run once all the above animations are finished
// your callback (things to do after all animations are done)
runNextAnimations();
});
jQuery를 사용할 수 있습니다. $.Deferred
var FunctionOne = function () {
// create a deferred object
var r = $.Deferred();
// do whatever you want (e.g. ajax/animations other asyc tasks)
setTimeout(function () {
// and call `resolve` on the deferred object, once you're done
r.resolve();
}, 2500);
// return the deferred object
return r;
};
// define FunctionTwo as needed
var FunctionTwo = function () {
console.log('FunctionTwo');
};
// call FunctionOne and use the `done` method
// with `FunctionTwo` as it's parameter
FunctionOne().done(FunctionTwo);
여러 지연을 함께 포장 할 수도 있습니다.
var FunctionOne = function () {
var
a = $.Deferred(),
b = $.Deferred();
// some fake asyc task
setTimeout(function () {
console.log('a done');
a.resolve();
}, Math.random() * 4000);
// some other fake asyc task
setTimeout(function () {
console.log('b done');
b.resolve();
}, Math.random() * 4000);
return $.Deferred(function (def) {
$.when(a, b).done(function () {
def.resolve();
});
});
};
첫 번째 함수 끝에 다음을 추가하십시오.
return $.Deferred().resolve();
이렇게 두 함수를 모두 호출
functionOne().done(functionTwo);
Yoshi의 답변과 함께 애니메이션에 대한 또 다른 매우 간단한 (콜백 유형) 솔루션을 찾았습니다.
jQuery에는 $ .timers 라는 노출 된 변수 (어떤 이유로 jQuery 문서의 어디에도 나열되지 않음)가 있으며,이 변수는 현재 발생하는 애니메이션 배열을 보유합니다.
function animationsTest (callback) {
// Test if ANY/ALL page animations are currently active
var testAnimationInterval = setInterval(function () {
if (! $.timers.length) { // any page animations finished
clearInterval(testAnimationInterval);
callback();
}
}, 25);
};
기본 사용법 :
functionOne(); // one with animations
animationsTest(functionTwo);
이것이 일부 사람들을 돕기를 바랍니다!
이것이 당신이 의미하는 바입니까? http://jsfiddle.net/LF75a/
당신은 하나의 함수가 다음 함수를 실행하도록 할 것입니다. 즉, 다른 함수 호출을 추가 functionONe
하고 그 아래에 당신을 추가하십시오 .
내가 놓친 게 있으면 알려줘, 원인에 맞길 바래 :)
or this : 이전 함수가 완료된 후 함수 호출
암호:
function hulk()
{
// do some stuff...
}
function simpsons()
{
// do some stuff...
hulk();
}
function thor()
{
// do some stuff...
simpsons();
}
이 답변은 표준 promises
의 JavaScript 기능인을 사용합니다 ECMAScript 6
. 대상 플랫폼이를 지원하지 않는 promises
경우 PromiseJs로 폴리 필하십시오 .
애니메이션 호출에서 Deferred
사용하여 애니메이션에 대해 jQuery가 생성 하는 객체 를 가져올 수 있습니다 .promise()
. Deferreds
이를 ES6Promises
로 래핑하면 타이머를 사용하는 것보다 훨씬 깔끔한 코드가 생성됩니다.
Deferreds
직접 사용할 수도 있지만 일반적으로 Promises / A + 사양을 따르지 않기 때문에 권장되지 않습니다.
결과 코드는 다음과 같습니다.
var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});
Note that the function in Promise.all()
returns the promise. This is where magic happens. If in a then
call a promise is returned, the next then
call will wait for that promise to be resolved before executing.
jQuery uses an animation queue for each element. So animations on the same element are executed synchronously. In this case you wouldn't have to use promises at all!
I have disabled the jQuery animation queue to demonstrate how it would work with promises.
Promise.all()
takes an array of promises and creates a new Promise
that finishes after all promises in the array finished.
Promise.race()
also takes an array of promises, but finishes as soon as the first Promise
finished.
ECMAScript 6 UPDATE
This uses a new feature of JavaScript called Promises
functionOne().then(functionTwo);
You can do it via callback function.
$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});
function function1(param, callback) { ...do stuff callback(); }
Here is a solution for n-calls (recursive function). https://jsfiddle.net/mathew11/5f3mu0f4/7/
function myFunction(array){
var r = $.Deferred();
if(array.length == 0){
r.resolve();
return r;
}
var element = array.shift();
// async task
timer = setTimeout(function(){
$("a").text($("a").text()+ " " + element);
var resolving = function(){
r.resolve();
}
myFunction(array).done(resolving);
}, 500);
return r;
}
//Starting the function
var myArray = ["Hi", "that's", "just", "a", "test"];
var alerting = function (){window.alert("finished!")};
myFunction(myArray).done(alerting);
You can use the javascript Promise
and async/await
to implement a synchronized call of the functions.
Suppose you want to execute n
number of functions in a synchronized manner that are stored in an array, here is my solution for that.
async function executeActionQueue(funArray) {
var length = funArray.length;
for(var i = 0; i < length; i++) {
await executeFun(funArray[i]);
}
};
function executeFun(fun) {
return new Promise((resolve, reject) => {
// Execute required function here
fun()
.then((data) => {
// do required with data
resolve(true);
})
.catch((error) => {
// handle error
resolve(true);
});
})
};
executeActionQueue(funArray);
'Program Tip' 카테고리의 다른 글
Python namedtuple을 json으로 직렬화 (0) | 2020.11.14 |
---|---|
전체 디렉토리에 대한 패치를 작성하여 업데이트하는 방법은 무엇입니까? (0) | 2020.11.14 |
내 gradle 빌드에 로컬 .aar 파일 추가 (0) | 2020.11.14 |
npm 설치시 최대 호출 스택 크기 초과 (0) | 2020.11.14 |
더 나은 Windows 명령 줄 셸 (0) | 2020.11.14 |