Home > Enterprise >  Run Js function only once after 2 seconds from c# code behind
Run Js function only once after 2 seconds from c# code behind

Time:08-03

Hello i have the next question, ive got the next function =

protected void lnk_Click( object sender, EventArgs e )
{
      LinkButton btn = sender as LinkButton;
      string text = btn.CommandName;
      ScriptManager.RegisterStartupScript( this, GetType(), "script", "alert('"  text   "');", true );


    }

I want to run the function after a second or 1.5 secs because this is running before the page renders visually, causing a "visual bug" on which the li tags (for example) dont get the css properties.

Any suggestion would help, thanks!

CodePudding user response:

In async you can wait using Task.Delay

private async Task<Response> ExecuteTask(Request request)
{
    var response = await GetResponse();

    switch(response.Status)
    {
        case ResponseStatus.Pending:
            await Task.Delay(TimeSpan.FromSeconds(2))
            response = await ExecuteTask(request);
            break;
    }
    return response;
}

CodePudding user response:

The JavaScript content should run on the event DOMContentLoaded like this:

document.addEventListener("DOMContentLoaded", function(){alert('text');});

If you're sure you want to use the "dirty" way, use setTimeout:

setTimeout(function(){alert('text');}, 1500); // 1500 milliseconds
  • Related