robieee
robieee

Reputation: 364

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 ?

Upvotes: 1

Views: 526

Answers (1)

Bas Slagter
Bas Slagter

Reputation: 9929

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

Upvotes: 1

Related Questions