admin管理员组

文章数量:1312838

How to call a function with addEventListener after setTimeout? Here is an example in code:

xyz = setTimeout(function () {
    [...blabla function...]
    // *(↓)
    if (window.addEventListener) {
        window.addEventListener('load', blabla, false);
    } else {
        window.attachEvent('onload', blabla);
    }
}, 3000);

*(→): addEventListener calls the function when page loads, but he should call the "blabla" function only after the setTimeout of 3s. So, how to fix this?

How to call a function with addEventListener after setTimeout? Here is an example in code:

xyz = setTimeout(function () {
    [...blabla function...]
    // *(↓)
    if (window.addEventListener) {
        window.addEventListener('load', blabla, false);
    } else {
        window.attachEvent('onload', blabla);
    }
}, 3000);

*(→): addEventListener calls the function when page loads, but he should call the "blabla" function only after the setTimeout of 3s. So, how to fix this?

Share Improve this question edited Dec 23, 2013 at 21:53 John asked Dec 23, 2013 at 18:17 JohnJohn 271 silver badge7 bronze badges 2
  • You call a function with addEventListener by triggering the event you've added a listener for. It's not really clear what you're trying to achieve here. Please state clearly what you expect to happen. – robertc Commented Dec 23, 2013 at 18:21
  • Not sure what you're trying to do here. The window's load event fires when the window is first loaded. Why do you need to add a handler for the event 3 seconds later? The event isn't going to fire again. – Barmar Commented Dec 23, 2013 at 18:21
Add a ment  | 

3 Answers 3

Reset to default 5

if you want to call a function 3 seconds after the window is loaded, you should put the setTimeout call in the handler:

function delayed_blah() {
    setTimeout(blabla, 3000);
}

if (window.addEventListener) {
    window.addEventListener('load', delayed_blah, false);
} else {
    window.attachEvent('onload', delayed_blah);

For your application, what you want to do is call the decrypt() function from the animation callback:

$('#dlbox').animate({
    'top': '0'
}, 1000, decrypt);

DEMO

The "load" event would have already fired even before the event handler is attached because of the delay.

May be this will help.

function blahblah(){
}
window.addEventListener("DOMContentLoaded",function(){
      setTimeout(blahblah,3000);
});

You can use jquery to achieve whatever you are demanding. The code is given below. In this, setTimeOut function is called when page has loaded pletely.

 $(function () {
        setTimeout(function () {
            blabla();
        }, 3000);
    });

本文标签: javascriptaddEventListener depending on setTimeoutStack Overflow