0

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()">
0

4 Answers 4

4

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();
};
Sign up to request clarification or add additional context in comments.

Comments

1

You can call the function with a timeout like this

setTimeout(base64_tofield, 3000);

2 Comments

tx - but now it submits the form every 3 seconds now by itself it seems.. do i put that outside the base64_tofield? function base64_tofield() { $('#formfield').val($.scriptcam.getFrameAsBase64()); document.form.submit(); }; setTimeout(base64_tofield, 3000);
Yes. Put it outside, otherwise its going to be recursive
1

"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.

Comments

1

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
}

Comments

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.