Rachel
Rachel

Reputation: 132558

How can I manually run a setTimeout timer immediately in javascript?

I have a form containing a Repeater which has a RadioButtonList and a TextBox. When a user changes the radio button or the text in one of the TextBoxes, the selected item and associated text for that Repeater item should get saved to the database.

Saving when a radio button changes is easy because of the .change() function, however for the TextBox I am creating a timer when the text changes that saves the data 2 seconds after the user stops typing

The problem is, if the user leaves the page or starts typing in a different TextBox before the timer executes, I need to manually execute the timer. How can I do that?

My javascript looks like this:

var typingTimer;                //timer identifier
var doneTypingInterval = 2000;  //time in ms, 2 second for example

$('textarea').on('input', function () {
    // Clear timer
    clearTimeout(typingTimer);

    // Set new timer to save form, passing current repeater item to Save method
    var parent = $(this).closest('.my-repeater-section');
    typingTimer = setTimeout(function () { saveForm(parent); }, doneTypingInterval);
});

Upvotes: 2

Views: 1192

Answers (2)

martskins
martskins

Reputation: 2940

Call your save function on blur, that way when the user leaves that textarea it will loose focus and if you listen to that event you can use your save function there

 $("textarea").blur(function(){
  //Call your save function here
});

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359816

A timer is just a delayed function call. So, name your function and you'll be able to call it "manually:"

var typingTimer;                //timer identifier
var doneTypingInterval = 2000;  //time in ms, 2 second for example

$('textarea').on('input', function () {
    // Clear timer
    clearTimeout(typingTimer);

    // Set new timer to save form, passing current repeater item to Save method
    var parent = $(this).closest('.my-repeater-section');

    function callback() {
        saveForm(parent);
    }

    typingTimer = setTimeout(callback, doneTypingInterval);

    // call it manually like usual:
    // callback();
});

Upvotes: 2

Related Questions