I have a couple functions using jQuery and I want to use await
, but it doesn't work. The await function()
is inside a while ()
. If that's the problem, how can I fix it? It is just two functions and the first is an async function.
I've tried to remove the while()
and instead test the same thing at the end of the function and if true
it would call itself again until false, but it runs incredebly fast(100's of times a second or faster) and that would cause problems. I've tried using promises, but I don't understand them so you can guess where that goes. I think I need a promise though, but I can't implement it.
The functions are as follows:
async function function1() {
q=0;
while (q<7) {
// calls another function to get values
await function2();
q ;
}
}
function function2() {
//jQuery here
$('.element').animate({
top: '100px',
left: '45vw'
});
return;
}
<html>
<body>
<p class='element' style='border: 2px solid black; width: 10vw; height: 10vw'></p>
</body>
</html>
Is there anything I can do?
This is a small script, it isn't my code exactly, just what is needed to remake the problem. It will run an animation over 7 different elements(incremented by q). I need it to wait because of not it will move them all at the same time, and I would prefer them to be moved one at a time. I've looked into promises, jQuery queues, and more. If it isn't possible, it won't hurt anything. I just want it to look nicer.
CodePudding user response:
You have to let function2 return a promise.
You can achive that by doing:
function function2()
{
return $('.element').animate({...}).promise();
}
CodePudding user response:
Try to add setTimeout or set where you want to