仅在我的间隔结束后才结束功能。 (JavaScript)

时间:2019-03-11 00:23:06

标签: javascript function intervals

我对我正在从事的个人项目有疑问。我需要为没有CSS的对象创建淡入和淡出效果,并且在间隔和函数上都遇到了麻烦,因为我需要先完成淡出功能,然后才能移至下一组函数。

// Interval parameters
var bgtInterval =       [0, false, 50];


// Fade functions will change fill following brightStep array values.

function fadeOut(){ 
  let i = 11;
  OBJECT.setAttribute("fill", brightSteps[i]);
  bgtInterval[1]=true;
  bgtInterval[0] = setInterval(function(){
    FULLCLOCK.setAttribute("fill", brightSteps[i]);
    if (i<=0){
      clearInterval(bgtInterval[0]);
      bgtInterval[1]=false;
    }
    i--;
  }, bgtInterval[2]);
}

function fadeIn(){
  let i = 0;
  OBJECT.setAttribute("fill", brightSteps[i]);
  bgtInterval[1]=true;
  bgtInterval[0] = setInterval(function(){
    FULLCLOCK.setAttribute("fill", brightSteps[i]);
    if (i>=11){
      clearInterval(bgtInterval[0]);
      bgtInterval[1]=false;
    }
    i++;
  }, bgtInterval[2]);
}

-

function resetSettings(id){
  fadeOut(); // I need fadeOut to finish before I move forward
  displayReset();
  displayShow();
  fadeIn(); // I need fadeIn to finish before I move out of this function
}

//THE MAIN FUNCTION//
resetSettings();
moreFunctionsHere();

谢谢!

1 个答案:

答案 0 :(得分:0)

使用Promises和async / await可以非常简单地实现

var bgtInterval =       [0, false, 50];


// Fade functions will change fill following brightStep array values.

function fadeOut(){ 
  // return the Promise
  return new Promise(resolve => {
    let i = 11;
    OBJECT.setAttribute("fill", brightSteps[i]);
    bgtInterval[1]=true;
    bgtInterval[0] = setInterval(function(){
      FULLCLOCK.setAttribute("fill", brightSteps[i]);
      if (i<=0){
        clearInterval(bgtInterval[0]);
        bgtInterval[1]=false;
        // resolve when done
        resolve();
      }
      i--;
    }, bgtInterval[2]);
  });
}

function fadeIn(){
  // return a Promise
  return new Promise(resolve => {
    let i = 0;
    OBJECT.setAttribute("fill", brightSteps[i]);
    bgtInterval[1]=true;
    bgtInterval[0] = setInterval(function(){
      FULLCLOCK.setAttribute("fill", brightSteps[i]);
      if (i>=11){
        clearInterval(bgtInterval[0]);
        bgtInterval[1]=false;
        // resolve when done
        resolve();
      }
      i++;
    }, bgtInterval[2]);
  });
}

// use async so we can await a Promise
async function resetSettings(id){
  // wait for fadeOut to finish
  await fadeOut();
  displayReset();
  displayShow();
  await fadeIn();
}

//THE MAIN FUNCTION//
// as we are in global scope, you can't use `async` ... so use Promise.then instead
resetSettings().then(moreFunctionsHere);

您会看到我在最后一行中使用.then,因为在全局范围内您不能使用await

您可以执行类似的操作

(async () => {
  await resetSettings();
  moreFunctionsHere();
})();

异步IIFE,因此您可以等待