如何在设置超时时存储数据并在时间到时检索它?
How to store data at the time of SETTING the timeout and retrieve it when the time is up ?
如何在设置超时时存储数据并在超时时检索?
运行 程序的步骤:
默认情况下,文本字段包含 apple
。
然后我点击 30 secs
按钮。
将文本字段更改为 ball
。
然后我点击 35 secs
按钮。
将提交的文本更改为 'cat' 。
然后我点击 45 secs
按钮。
function myFunction1() {
myVar = setTimeout(function() {
alertFunc(document.getElementById('age').value);
}, 30000);
}
function myFunction2() {
myVar = setTimeout(function() {
alertFunc(document.getElementById('age').value);
}, 35000);
}
function myFunction3() {
myVar = setTimeout(function() {
alertFunc(document.getElementById('age').value);
}, 40000);
}
function alertFunc(a) {
alert(a);
}
<input type="text" id="age" value="apple">
<input type="button" id="button2" value="30 secs" onClick=myFunction1()>
<input type="button" id="button3" value="35 secs" onClick=myFunction2()>
<input type="button" id="button4" value="40 secs" onClick=myFunction3()>
The result :
After roughly 35 secs the first alert will display cat .
Roughly 5 seconds later the second alert will also display cat.
And,oughly another 5 seconds later the third alert will also display cat !!!
我认为发生的事情是超时完成后正在记录参数。
我该如何克服这个问题?
我的一个想法是,在设置计时器时,我会将参数值推送到 stack/array 上,然后在计时器完成时将其弹出。但是我如何在计时器完成时识别它。
不确定如何在此处实施 promise-then
方法。
请帮忙。
如果您希望超时函数在添加时显示值,您应该将 myFunctionX 更改为此
function myFunction2() {
var v = document.getElementById('age').value;
myVar = setTimeout(function() {
alertFunc(v);
}, 35000);
}
您的代码的问题是当达到超时时,回调函数从 dom 读取值,这是执行您的步骤的最终值。
如何在设置超时时存储数据并在超时时检索?
运行 程序的步骤:
默认情况下,文本字段包含 apple
。
然后我点击 30 secs
按钮。
将文本字段更改为 ball
。
然后我点击 35 secs
按钮。
将提交的文本更改为 'cat' 。
然后我点击 45 secs
按钮。
function myFunction1() {
myVar = setTimeout(function() {
alertFunc(document.getElementById('age').value);
}, 30000);
}
function myFunction2() {
myVar = setTimeout(function() {
alertFunc(document.getElementById('age').value);
}, 35000);
}
function myFunction3() {
myVar = setTimeout(function() {
alertFunc(document.getElementById('age').value);
}, 40000);
}
function alertFunc(a) {
alert(a);
}
<input type="text" id="age" value="apple">
<input type="button" id="button2" value="30 secs" onClick=myFunction1()>
<input type="button" id="button3" value="35 secs" onClick=myFunction2()>
<input type="button" id="button4" value="40 secs" onClick=myFunction3()>
The result : After roughly 35 secs the first alert will display cat . Roughly 5 seconds later the second alert will also display cat. And,oughly another 5 seconds later the third alert will also display cat !!!
我认为发生的事情是超时完成后正在记录参数。
我该如何克服这个问题?
我的一个想法是,在设置计时器时,我会将参数值推送到 stack/array 上,然后在计时器完成时将其弹出。但是我如何在计时器完成时识别它。
不确定如何在此处实施 promise-then
方法。
请帮忙。
如果您希望超时函数在添加时显示值,您应该将 myFunctionX 更改为此
function myFunction2() {
var v = document.getElementById('age').value;
myVar = setTimeout(function() {
alertFunc(v);
}, 35000);
}
您的代码的问题是当达到超时时,回调函数从 dom 读取值,这是执行您的步骤的最终值。