gpt4 book ai didi

javascript - 使用 setTimeout 从创建 setTimeout 时恢复变量值?

转载 作者:行者123 更新时间:2023-11-30 16:29:50 25 4
gpt4 key购买 nike

编辑:我最终想在以后使用 setTimeout 恢复变量的先前值

我创建了以下示例来说明我的观点:( JSFiddle )

<!DOCTYPE html>
<html>
<body>
<p>Push the button</p>
<button id = "push">Try it</button>

<script>
var x = {};
x.boo = "foo";
function myFunction() {
alert(x.boo);
}
document.getElementById('push').addEventListener('click',function() {
setTimeout(function() {
myFunction(x)
}, 1000);

x.boo = 'baz'; //eg. something else modifies x before first timer runs out
// another timer gets created, should reflect new value in x
// added delay is just to keep track of the order myFunction is being executed
setTimeout(function() {
myFunction(x)
}, 3000);
},false‌​);
</script>
</body>
</html>

发生了什么:

点击按钮后,alert() 窗口在 1 秒后显示“baz”,然后在 3 秒后显示“baz”。

我想要发生的事情:

点击按钮后,警告窗口应显示“foo”,然后在 3 秒后显示“baz”。

我尝试将 myFunction 回调包装在另一个发送到 setTimeout 的匿名函数中,并尝试传入参数,这两者都不会改变行为。

在我的应用程序中,加载了 jQuery 库,因此如果需要我也可以使用它。

最佳答案

你有没有试过这样的事情:

var x = {};
x.boo = "foo";
function myFunction(x2) {
alert(JSON.stringify(x2));
}
$('#push').on('click', function() {
// Deep copy
var newObject = jQuery.extend(true, {}, x);
setTimeout(function() { myFunction(newObject); }, 1000);
x.boo='baz';
setTimeout(function() { myFunction(x); }, 3000);
});

用这种方法更新了 fiddle:

http://jsfiddle.net/vijayP/dwzxjco6/7/

关于javascript - 使用 setTimeout 从创建 setTimeout 时恢复变量值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492157/

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