user3362580
user3362580

Reputation: 31

setInterval not working correctly

I'm trying to get it so the confirm window pops up every n seconds that the user inputs into the prompt but the confirm window pops up immediately regardless of the input. What am I doing wrong?

Here is what my button looks like:

<button onclick="timer_prompt()">FUN</button>

my simple functions:

function timer_prompt()
{
    var seconds = prompt("Enter Time Interval In Seconds Please");
    seconds = seconds*1000;
    if(seconds>0)
    {
     setInterval(confirm_timer(), seconds);
    }
        else
        {
        alert("You entered invalid content");
        }

} 


function confirm_timer()
{
    confirm("YOU HAVE SET A TIMER!!!");
}

Upvotes: 0

Views: 751

Answers (3)

Why not try this way?

function timer_prompt() {
    var seconds = prompt("Enter time interval in seconds please.");
    seconds = seconds * 1000;

    if(seconds > 0) {
        callInterval(seconds);
    } else {
        alert("You entered invalid content");
    }
}


function callInterval(seconds) {
    setTimeout(function() {
        confirm("You have set a timer!");
        callInterval(seconds);
    }, seconds);
}

timer_prompt();

Upvotes: 0

Brennan
Brennan

Reputation: 5732

setInterval takes a function as its first argument, you are passing the return value of the function. Remove the parentheses from confirm_timer in the setInterval

Upvotes: 1

epascarello
epascarello

Reputation: 207501

You are calling, not assigning

setInterval(confirm_timer(), seconds);

needs to be

setInterval(confirm_timer, seconds);

Upvotes: 6

Related Questions