I'm having problems with this JS functions:
function unfade(element, callback) {
var op = 0.1; // initial opacity
element.style.filter = 'alpha(opacity=0)';
element.style.opacity = 0;
element.style.display = 'block';
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
function fade(element, callback) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 10);
}
function fadeAndUnfade(element2fade, element2unfade) {
fade(element2fade);
unfade(element2unfade);
}
If I call the function fadeAndUnfade(...) then it should run fade(...) and once it's done it should run unfade(...). But both of this functions run at the same time.
Could someone please explain me why? I don't see any reason why they sould run async...
Thank you very much :)
EDIT:
As mentioned from Robin Zigmond, setInterval is an async function: I tried
...
var timer = await setInterval(...
but it gave me in Firefox debug this error: Uncaught SyntaxError: await is only valid in async functions, async generators and modules
How can i make this functions then not async?
setIntervalwhich is one of the fundamental async API's in Javascript.setTimeout(run once, after a delay) rather thansetInterval(run repeatedly with the given time interval in between). And to do only haveunfaderun after thefade(including timeout) has completed, the easiest way is probably to convert them into promises and then you can useasync/await, or.then(...)var timer = await setInterval(..." - see usingawaitwithsetTimeout. Notice that you cannot usesetIntervalwith promises - but you can simply write a loop instead (like in this example).