gpt4 book ai didi

Javascript 闭包和 setTImeInterval 函数

转载 作者:行者123 更新时间:2023-11-28 01:49:59 24 4
gpt4 key购买 nike

<!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 varibale 的值变为 1,2,3,4,5。此代码不返回 DelayedValue 变量的值。

请指出我做错了什么?

最佳答案

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

您可以这样做,例如( 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;
});

关于Javascript 闭包和 setTImeInterval 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19809508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com