编辑:我最终想要使用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);
});


使用这种方法更新了小提琴:

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

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

10-13 08:52