2

I have an input of type text where I add a value.

<input type="text" name="mydat" id="mydat" value="60000" />

This I have a timer which runs every minute.

<script>

window.setInterval(function(){

 //do something here

}, 60000);

</script>

In the code above the interval value is hardcoded.

How can I do this instead:

60000 = #mydat value

So, everytime it loops it reads the value from #mydat ?

3 Answers 3

7

Use setTimeout recursively instead.

var startTimer = function() {
    console.log("do something here");
    window.setTimeout(startTimer, parseInt($("#mydat").val(), 10));
});

startTimer();
Sign up to request clarification or add additional context in comments.

1 Comment

+1 nice and clean, but don't forget about .val() and the radix parameter
5

"Every time it loops" implies that the value might change - so setInterval is incorrect, you'd need to use setTimeout repeatedly...

function DoSomething() {
    //Do Stuff
    setTimeout(DoSomething, document.getElementById('mydat').value);
}

should do what you need and update the timeout if the contents of the textbox changes (after the next event fires)

Comments

2

You can retrieve the value of an input using the value attribute.

var interval = document.getElementById('mydat').value;

window.setInterval(function() {
    // Some code...
}, interval);

or using jQuery

var $interval = $('#mydat').val();

window.setInterval(function() {
    // Some code...
}, $interval);

2 Comments

Note that this will read the value from mydat on the first iteration; when the user types a different number, it won't adjust the interval.
This seems odd, you asked How can I do this instead... so everytime it loops it reads the value from #mydat This answer does not do that. As dbaseman pointed out, it only reads it ones not everytime.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.