1
<!DOCTYPE html>
<html>
<body>

<script>
function sampleDelay(delay) {
  return function(functionArray) {
    var count = 0;
    var func = setInterval(function(){
    if(count === functionArray.length){
      clearInterval(func);  
    }
          count++;
    console.log(functionArray[count-1]);
      return functionArray[count-1];        
    }, delay);

  };
}


var DelayedValue = sampleDelay(1000)([
  1,2,3,4,5
]);
</script>

</body>
</html> 

我希望延迟一秒后将 DelayedValue 变量的值设为 1,2,3,4,5。此代码不返回 DelayedValue 变量的值。

请建议我做错了什么?

4

1 回答 1

1

这是因为您通过引入间隔使代码异步。当间隔仍在运行时,您的函数已经完成执行。您需要使用回调和/或承诺来解决这个问题。

例如,您可以这样做(小提琴):

function delayedOutput(values, delay, callback){
    var step = 0,
        interval = setInterval(function(){
            callback(values[step++]);

            if(step === values.length){
                clearInterval(interval);
            }
    }, delay); 
}

delayedOutput([1,2,3,4,5], 1000, function(i){
    document.getElementById('output').innerHTML += i;
});
于 2013-11-06T10:29:14.290 回答