FstaRocka
FstaRocka

Reputation: 278

Delay jquery function / form submit

im struggling to get a function to be delayed for 3 seconds.. this is on an image -

 function base64_tofield() {

            $('#formfield').val($.scriptcam.getFrameAsBase64());

             document.form.submit();
           };

ive tried:

setTimeout( function () { 
          base64_tofield(); 
           }, 3000);

to no avail. the form is just submitting without the 3 second delay - any ideas? do i need to 'block' the form or what?

thanks!

image code:

<img id="btn1" onclick="base64_tofield()">

Upvotes: 0

Views: 453

Answers (4)

Andri
Andri

Reputation: 1503

You can use window.setTimeout() for this. setTimeout returns a timeoutID that you can use to cancel the action before it's triggered.

If you are setting the timeout inside a jquery callback function, you should wrap the target function call into an anonymous function, instead of just entering the target function name.

var delay = 3000;
var timeoutID = setTimeout(function(){base64_toField();},delay);

//if you need to cancel the function call before it's triggered:
clearTimeout(timeoutID);

Edit: I just read that your form submits without the 3 second delay. you should suppress the default action on the event:

$("form").submit(function(e) {
    e.preventDefault();
    //do other stuff
}

Upvotes: 1

Tim Vermaelen
Tim Vermaelen

Reputation: 7059

"do i need to 'block' the form or what?"

Euh, yes that sounds like an idea. Right now you define your function base64_tofield() directly without the use of jquery. Any reason for that?

In jQuery the event parameter is added which allows you to do event.preventDefault()

$("#btn1").click(function(event){
    // do i need to 'block' the form or what?
    event.preventDefault();
    setTimeout(base64_tofield, 3000);
});

Not sure how your images are added to the page but a css class instead of an id and/or .on() can help here too.

Upvotes: 1

NaYaN
NaYaN

Reputation: 1320

Live Demo : alert will popup after 3 secs.

Try this:

<img id="btn1" onclick="new_fun()">

function new_fun()
{
    setTimeout( function () { 
          base64_tofield(); 
    }, 3000);
}

function base64_tofield() {
    $('#formfield').val($.scriptcam.getFrameAsBase64());
    document.form.submit();
};

Upvotes: 4

Sajuna Fernando
Sajuna Fernando

Reputation: 1384

You can call the function with a timeout like this

setTimeout(base64_tofield, 3000);

Upvotes: 1

Related Questions