简体   繁体   中英

Javascript closure and setTImeInterval function

<!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> 

I want to get the values of DelayedValue varibale to be 1,2,3,4,5 after a delay of one second. This code is not returning values of DelayedValue variable.

Please suggest what i am doing wrong ?

This is because you made your code asynchronous by introducing the interval. Your function already finished executing while the interval is still running. You need to work with callbacks and/or promises to solve this.

You can do it like this for example ( fiddle ):

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;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM