156

I'm trying to implement the Facebook's logout functionality in my project. Login works just fine. But I'm facing the getting the following message in JavaScript console with the logout code.

[Violation] Long running JavaScript task took 318ms session.php:51 1 sdk.js:135

[Violation] Handler took 83ms of runtime (50ms allowed)

I've tried to search for other similar threads and those solutions didn't work out for me. I tried removing parts of my code and see which part is giving problem. Its quite clear that its getting the error due to Facebook's JS SDK as seen in the message. I've also disabled all of my Chrome extensions.

The code works fine in Firefox but not in Chrome, nor in Opera. Is there any method for me to extend this timeout duration? Or any other method to fix this issue in chrome. Here is my code for logout.

<?php
    session_start();
    //echo $_SESSION["current_user"];
    //echo $_COOKIE["current_user"];
    session_destroy();
    unset($_COOKIE["current_user"]);
    setcookie("current_user","",time() -3600, "/","", 0);
    //header("location: login.php");
?>

<!doctype html>

<html>
<head>
</head>
<body>

<script>

    // Default settings
    window.fbAsyncInit = function() {
        FB.init({
            appId      : '<app-id>',
            cookie     : true,
            xfbml      : true,
            version    : 'v2.8'
        });
        FB.AppEvents.logPageView();   
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    window.onload = function(){
        logout();
    }
    function logout(){
        console.log("1");
        FB.getLoginStatus(function(response) {
        if (response.status === 'connected') {
            FB.logout();
            console.log("2");
            window.location="login.php";
            console.log("3");
        }
        else{
            console.log("4");
            window.location="login.php";
            console.log("5");
        }
        });
    }
</script>
</body>
</html>

For obvious reasons I've removed the App-Id from the code. Any help is appreciated. :)

norbitrial
  • 14,716
  • 7
  • 32
  • 59
FreeKrishna
  • 1,833
  • 2
  • 12
  • 21
  • 3
    It is just a warning, you dont have to care about it, your code still will work. – NoNameProvided Feb 23 '17 at 11:21
  • 1
    @NoNameProvided But the logout function does not work in Chrome. It fails to redirect to the login.php page in Chrome. – FreeKrishna Feb 23 '17 at 11:23
  • 6
    Event if it's not work, it doesn't related to the Violation messages. They are only informal, and have no effect on your code. – NoNameProvided Feb 23 '17 at 11:24
  • 1
    @NoNameProvided Then how come the code works in Firefox, but not in Chrome? I've checked the code, its correct. You can have a look yourself. – FreeKrishna Feb 23 '17 at 11:26
  • As @NoNameProvided said, it's not the issue. Warnings don't affect anything. It's simply a feature that Chrome has that Firefox doesn't (to my knowledge). Are you seeing any network errors in the timeline? – Jarrod Mosen Mar 08 '17 at 03:14
  • 1
    Here's my guess: your `window.onunload` is getting overwritten. Try using Chrome in an incognito window. I've had issues where my Chrome extensions were adding javascript that changed the way my application ran. If so, consider using something to add to the window.unload event without using the window.unload function itself, such as: `$( window ).on('unload', function() { return "Handler for .unload() called."; });` – StingeyB Mar 08 '17 at 06:19
  • Nope, according to this thread(https://productforums.google.com/forum/#!topic/chrome/HgQgIKLaShE;context-place=forum/chrome) the violation may stop script execution, I'm still trying to find the bug and how to disable this behavior on chrome. – Flavio Garcia May 05 '17 at 15:49
  • 3
    It seems to be a duplicate: https://stackoverflow.com/questions/41218507/violation-long-running-javascript-task-took-xx-ms/41218580 – oklas Jun 30 '17 at 07:50
  • Possible duplicate of [Violation Long running JavaScript task took xx ms](https://stackoverflow.com/questions/41218507/violation-long-running-javascript-task-took-xx-ms) – Mark Schultheiss Oct 31 '19 at 11:21
  • @FreeKrishna you should accept one of these answers. – Raydot Aug 17 '23 at 17:47

10 Answers10

285

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

mahemoff
  • 44,526
  • 36
  • 160
  • 222
70

Perhaps a little off topic, just be informed that these kind of messages can also be seen when you are debugging your code with a breakpoint inside an async function like setTimeout like below:

[Violation] 'setTimeout' handler took 43129ms

That number (43129ms) depends on how long you stop in your async function

Reza
  • 3,473
  • 4
  • 35
  • 54
  • 19
    Thanks to this comment I was able to find this topic and get an answer, off topic or not, it was very useful. – stramin Oct 06 '20 at 21:19
  • I was experiencing this warning when using webpack-dev-server but the the issue only affected the development environment. It was fine in the production build – andrew Apr 22 '21 at 09:23
  • is it always in an async function? im facing somewhat the same issue `[Violation] 'click' handler took 310ms` and im not using any asynchronous functions. but instead the click fetches a different state from the store (language change) – Sarkis Jul 28 '23 at 04:19
16

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105
16

As no one has answered how to make it go away... Turns out, if your handler is an async function with an await method, it will suppress the message.

const sleep = (s) =>
  new Promise((p) => setTimeout(p, (s * 1000) | 0))

async function timeoutHandler() {
  await sleep(1)
  ... // heavy duty code here
}

setTimeout(timeoutHandler, 10000)

If you're doing this a lot... it is probably best to replace sleep(1) with a dedicated suppressor method. I just happen to have sleep laying around in my utils for debugging race conditions.

Ray Foss
  • 3,649
  • 3
  • 30
  • 31
  • 3
    The point of long running JS warnings is to reduce the UI blocking. Making your code async by using `setTimeout()` is how you do that. Network requests and some other APIs are also natively asynchronous. – Brenden Oct 05 '21 at 05:50
14

This warning: [Violation] 'setTimeout' handler took 126ms is exactly what it says, you had a handler that builds up from mostly synchronous calls and it took 126ms for your computer to process it.

Since JavaScript is not multi-threaded and every synchronous task blocks the UI, a 100ms synchronous task is quite noticeable. (60FPS is 16ms)

So you have to be serious about this warning because it means your UI is lagging.

To solve this problem, you have to split the problematic task into multiple small tasks. You can do this by starting async jobs because every async job will go to the end of the queue, so they will be processed later, leaving compute space for the UI.

Dávid Bíró
  • 336
  • 3
  • 6
  • 2
    This should be the accepted answer. Exactly explained the reason and seriousness of this warning and explain how to fix it. Thank you! – Pam Stums Aug 12 '22 at 14:55
8

This answers only why we see this message.

By default, Verbose is off.

Verbose is on

When Verbose is set to On, we see this message.

So unless you have serious performance issues, we can turn it back to its default settings of Off, in which case I didn't see the message anymore, not anymore obstructing my own log messages.

Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
3

If one wants to get rid of the warning by changing the handler's code to asynchronous one (which of course will be acceptable only in case subsequent code doesn't depend on the handler to finish), then the only possible solution seems to be to return Promise.resolve().then(() => {/ * your handler's code here * /}).

At least in my case, when a window.confirm() call was used in the handler, nothing else helped: neither returning new Promise(), nor declaring the handler as async, nor setting a timeout in it. One can try it by commenting/uncommenting sections below

<button id="click">click me</button>
<script>
  'use strict';
  const btn = document.getElementById('click');
  //btn.addEventListener('click', async (e) => {
  //  window.confirm('wait before clicking');
  btn.addEventListener('click', (e) => {
    return Promise.resolve().then(() => {
      window.confirm('wait before clicking');
    });

    //return new Promise((resolve) => {
    //  window.confirm('wait after click');
    //  resolve();
    //});

    //setTimeout(() => {
    //  window.confirm('wait before clicking');
    //}, 0);
  });
</script>
d.k
  • 4,234
  • 2
  • 26
  • 38
  • This was the most straightforward answer for me. Offloading my prompt to a post-promise anon function eliminated the message with minimal boilerplate. – Joe Still Jan 28 '23 at 16:08
2

If you are debugging your source code and you raise an alert for debugging, the response from the called function is slow in coming and causes this message. Delete the alert momentarily and redo the code to make sure that without this alert is the source of the message.

  • This caused the problem for me. One solution is to write an async function to call 'alert' (or a Promise). Then the alert won't happen during the event callback but rather during idle time. – David Spector Aug 20 '23 at 17:39
1

I realize I could just ignore this violation. But, when I tried the answer by Ray Foss, the violation went away!

I borrowed his sleep function, then added "await sleep(1)" as the first line of the function causing the violation message. The code still runs fine, and the violation message is no longer displayed in the console!

I had to make one change to Ray's example. The function that is being declared as an async function still needs the "function" keyword.

So, in Ray's example, "async timeoutHandler()" should be "async function timeoutHandler()". Once I made that change, the code ran fine.

Note: Technically, my function is now a little slower, due to the calling the sleep(1) function. But, it's not noticeable, and in my opinion, it's worth the overhead to make the violation message go away.

rtrimble
  • 19
  • 4
  • 2
    This isn't an answer and would be better suited as a comment on the post you're referring to. – Madbreaks Nov 29 '21 at 17:37
  • 3
    I don't yet have the reputation to comment on a post. But, I wanted to specify that a slight tweak was needed to get another user's answer to work. I agree this would be better suited as a comment, and will do so in the future once I'm worthy. – rtrimble Nov 30 '21 at 18:43
1

This is a warning only and it is informing that there is a delay or a wait to continue with the code a (Future). As they said in a comment above this can be triggered by a simple alert and you can test it by placing it in the middle of your JS code where it waits for the user's response.

if for example you place an alert("I wait for you") you will see that the faster you are to give ok it will decrease the time in the warning "[Violation]'change' handler took 1496ms".

in your case this is happening because you have a connection check "(response.status === 'connected')" this should wait for a connection response.

  • 1
    @Bot ... it makes no sense for a Bot to comment on a post for which the Edit is full. – MeSo2 Feb 24 '23 at 16:43