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

Use setTimeout to restore variable values from when setTimeout is created?

编辑:我最终想在以后使用 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() window 1 秒后显示 'baz',3 秒后显示 'baz'。

我想要发生的事情:

点击按钮后,警报 window 应显示 '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/

我不知道这是你想要的还是看看 it.First 单击它会显示一个警报 foo 然后在 3 秒后它会显示 baz alert.have 看看在这个代码

 <!DOCTYPE html>
 <html>
 <body>
 <p>Push the button</p>
<button onclick="myFunction();x.boo='baz';setTimeout(myFunction, 3000,x);">Try it</button>

  <script>
  var x = {};
  x.boo = "foo";
  function myFunction() {
  alert(x.boo);
 }
</script>
</body>
</html>

像这样更改您的代码:

<!DOCTYPE html>
<html>
<body>
<p>Push the button</p>
<button onclick="setTimeout(myFunction, 1000);setTimeout(myFunction, 3000);">Try it</button>

<script>
var x = {};
x.boo = "foo";
function myFunction() {
    alert(x.boo);
    x.boo = "baz";
}
</script>
</body>
</html>