如何在执行之前保留 setTimeout 参数值? [英] How to preserve setTimeout parameter value until execution?

查看:31
本文介绍了如何在执行之前保留 setTimeout 参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以在按键上执行并在用户键入时将数据保存到数据库中.

I have a bit of code that executes on keypress and saves data to a database as the user types.

我添加了一个 setTimeout 函数,在它前面有一个 clearTimeout ,这样用户输入的每个字符都不会发送 Ajax 请求来保存数据.

I added a setTimeout function with a clearTimeout infront of it so not EVERY single character the user enters is sending out an Ajax request to save data.

虽然 setTimeout 对一个输入字段非常有效,但如果用户决定快速切换输入字段(在 setTimeout 延迟结束之前),传递给 callSomeAjax 的参数会在函数执行之前发生变化.

While the setTimeout works great for one input field , if the user decides to switch input fields quickly (before the setTimeout delay is up) the parameter passed to the callSomeAjax changes before the function is executed.

正在发生的事情的简化版本...

Simplified version of what's happening...

var a = 1; //some user data

//function to call ajax script to save data to database
function callSomeAjax(a)
{
   console.log(a);
}

setTimeout(function(){callSomeAjax(a)},1000); //executes callSomeAjax after 1 second delay

a=3; //change user data before callSomeAjax executes

// Result of console.log is 3, not 1 like I want it to be...

小提琴代码

有什么想法吗?

推荐答案

问题是 setTimeout 直到 1 秒后才运行传入的函数.a 发生了什么变化,所以当 callSomeAjax(a) 运行时,a 是它的新值.

The problem is that setTimeout doesn't run the function passed in until 1 second has passed. What that does happen a has changed, so when callSomeAjax(a) is ran, a is at its new value.

您需要在调用 setTimeout 之前捕获(在闭包中)a 的值.

You need to capture (in a closure) the value of a before calling setTimeout.

var a = 1;

function show(a) {
    console.log(a);
}

(function(a){
    setTimeout(function () {
        show(a)
    }, 1000);
}(a));

a = 3;

演示:http://jsfiddle.net/U59Hv/2/

这篇关于如何在执行之前保留 setTimeout 参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆