Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird problem with setTimeout() on Google Chrome

I searched here and found a quick solution to call an action when the user is idle on the page. It basically works well on all browsers.

But when I use an alert or a confirm dialog on the page, the weird problem occurs on Google Chrome.

After the alert or confirm box disappears (Pressed OK, Cancel or Cross), the idle function works unexpectedly.

  • After the box confirm or alert box disappears, which came from the link's onclick, I got '3 seconds passed' box immediately

Tested on FF,IE and Chrome (Latest). It just occurs on Chrome.

My code is here: http://jsbin.com/ifule3

  window.onload = idleTimer;
  function idleTimer() {
    var idleDuration;
    document.onmousemove = idleReset;
    function  idleReset() {
      if (idleDuration) {
        clearTimeout(idleDuration);
        idleDuration = 0;
      }
      idleDuration = setTimeout(function() {
        alert('3 seconds passed.');
      }, 3000)
    }
  };

<a onclick="if(confirm( '?' )) { alert('Ok Pressed.') } else { return false; };">First Link!</a>
<a onclick="alert('test');" >Second Link!</a>

It seems my explanation is not enough :/

I changed the code with jQuery;

jQuery(document).ready(function() {
    var idleDuration;
    jQuery(document).mousemove(function() {
        if (idleDuration) {
            clearTimeout(idleDuration);
            idleDuration = 0;
        }

        idleDuration = setTimeout(function() {
            someIdleAction();
            window.location = 'some url';
        }, 3000)
    })
});

When I put this code on my page.It works like a charm. I open the page, make some mouse actions or not, then 3 seconds without moving mouse, I got the idle alert.This is what I need.

When I put a link that simply calls an alert box and click on it, alert box appears. Then I close the box and I got the idle alert which is '3 seconds passed'.

    <a onclick="if(confirm( 'Are you OK?' )) { alert('Nice.') } else { return false; };">First Link!</a>
    <a onclick="alert('An alert.');" >Second Link!</a>

It just occurs on google chrome. With IE and FF everything is fine. Increasing the timeout, nothing changes.

like image 453
egon Avatar asked Sep 24 '10 12:09

egon


1 Answers

If you're getting the box immediately after dismissing the alert or confirmation, that's not odd, that's normal. confirm and alert completely stop JavaScript execution. The next call to the timer will queue up waiting for the interpreter to become available again, so dismissing the box bringing up the message doesn't surprise me. Is that the only behavior you're seeing that's a problem?

like image 177
T.J. Crowder Avatar answered Sep 21 '22 08:09

T.J. Crowder