DannyBoi DannyBoi - 1 year ago 68
HTML Question

How to store data at the time of SETTING the timeout and retrieve it when the time is up ?

How to store data at the time of SETTING the timeout and retrieve it when the time is up ?

Steps to run the program:
By default the text field contains

apple
.
Then I click on the
30 secs
button .
Change the text field to
ball
.
Then I click on the
35 secs
button .
Change the text filed to 'cat' .
Then I click on the
45 secs
button .



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 !!!


I think what is happening is the parameter is being recorded after the timeout is complete.

How do i overcome this ?

One idea I have, is when setting the timer I will push the parameter value onto a stack/array and then pop it when the timer is complete. But how do I identify the timer when it completes.

Not sure how to implement
promise-then
method here.

Please help.

Answer Source

If you want your timeout function display the value when they are being added, you should change the myFunctionX to this
function myFunction2() { var v = document.getElementById('age').value; myVar = setTimeout(function() { alertFunc(v); }, 35000); } The problem of your code is when the timeout is reached, the callback function read the value from dom, that is the final value of doing your steps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download