简体   繁体   中英

setTimeout not working in Chrome

This question is for a colleague. He is having an issue in Chrome with the following code snippet:

function showEmailClient(emailContent, url, providerContactId) {
    window.location = emailContent;
    if (providerContactId != undefined) {
        setTimeout(function() {
            clientSideRedirect(url + providerContactId);
        }, 5000);
    }
    else {
        setTimeout(function() {
            clientSideRedirect(url);
        }, 5000);
    }
}​

The setTimeout functions are getting called immediately in Chrome instead of waiting the five seconds they are supposed to. Any ideas?

Update

emailContent is a mailto string, eg 'mailto:support@somewhere.com' which causes the user's default mail client to open, not the page to redirect.

window.location = emailContent;

一旦命中此行,这将重定向浏览器。

From my experience, don't use use a window.location for bringing up the email client and doing a redirect on the same page - it's a beast. Instead, use a form for submitting the email using the System.Net.Mail namespace and objects in it, then do your redirect. If that isn't an option, store the mailto data in session, redirect and then call the mail client when the page loads. The only caveat about this approach is that the window.location will kill any responses that haven't been written, so you'll need to give the page some time to load using a timer event usually about 2000 milliseconds (if your page has dynamic data and has various load times, good luck!).

This code snippet uses jQuery to wait for the document to be ready for use and adds 2000 milliseconds to ensure any responses are written.

function showEmailClient(mailto)
{
    $(document).ready(function ()
    {
        setTimeout(function ()
        {
            window.location = mailto;
        }, 2000);               
    });
}

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["SendMail"] != null)
    {
        var mailto = Session["SendMail"].ToString();
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "ShowEmailClient", "showEmailClient('" + mailto + "');", true);
        Session["SendMail"] = null;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM