Dantès Cristo
Dantès Cristo

Reputation: 183

jQuery change time of setInterval using range input

I am trying to access the time value of setInterval, however I am new in jQuery and JavaScript and I am not sure how can I achieve this. Here is what I have for now:

<form name="form4" oninput="amount.value=rangeInput.value">
    <input type="range" id="rangeInput" value="1000" name="rangeInput" min="1000" max="10000" step="500"/>
    <output name="amount" for="rangeInput">1000</output>
</form>

And the code would be:

$(function randomName() {
    setInterval(function(){ 
        //alert("some text");
    }, 10000);
});

Here is a fiddle of what I have for now https://jsfiddle.net/mLk3wb50/

Is there a way to change the value of time, link it to the range input?

Basically, I would like to execute the alert or whatever action at intervals set by the range input. Is this possible? Thanks!

Upvotes: 1

Views: 3055

Answers (2)

Gaurang Tandon
Gaurang Tandon

Reputation: 6753

This seems to be the way. You will need to clear the interval before reinitializing it.

function someFunc(){ alert("hi"); }
var interval;

$(function randomName() {
    interval = setInterval(someFunc, 10000);;    
});

$("#rangeInput").on("change", function(){
    clearInterval(interval);
    interval = setInterval(someFunc, $(this).val());
});

FIDDLE

Upvotes: 5

Amir Popovich
Amir Popovich

Reputation: 29836

Here's a way to change the interval:

 function myFunc(){ alert('hi'); }

 var myInterval = setInterval(myFunc, 1000);

 function changeInterval(){
    clearInterval(myInterval);
    myInterval = setInterval(myFunc, 2000);
 }

Upvotes: 1

Related Questions