简体   繁体   中英

setTimeout fires twice or not in Javascript

I have this code:

window.setTimeout(function() {
    let sudokuBodyWidth = $sudokuBody.outerWidth(true);
    let sudokuBodyHeight = $sudokuBody.outerHeight(true);

    console.log(sudokuBodyWidth + ',' + sudokuBodyHeight);

    $sudoku.hide();
    $welcomeOverlay.css({
        width: sudokuBodyWidth,
        height: sudokuBodyHeight
    }).show();
}, 800);

window.clearTimeout();

I've put this code in a setTimeout because it takes a lot of time the DOM to load, so the JS code is to early with executing and returns 0 for the values (it's a huge codebase and I'm not 'allowed' to change the site structure to make the JS load later).

The problem is that this code runs twice. First, it returns the correct result, but then it returns 0 for both variables immediately after the correct values. As you can see, I've added a clearTimeout to prevent the execution to happen twice. But it keeps executing twice.

I've also tried:

let welcomeTimeout = setTimeout(function() {
    // the code
});

clearTimeout(welcomeTimeout);

When doing this, the code doesn't execute at all.

如果两次加载脚本,它只应执行一次检查Ur代码库,然后将clearTimeout代码放在setTimeout函数提供的匿名函数的末尾

window.clearTimeout() will do nothing because you are not passing the timerId witch get returned by window.setTimeout() and this should not run twice there is something else witch is causing this function to run twice

and in second one clearTimeout(welcomeTimeout); clears the timer that's why your code doesn't run

if you want to run your code after the document get loaded fully then you can use window.onload = function(){...}

or if you are using jQuery then you can also try $(document).ready(function(){...})

Putting the code at the end of HTML executes it when the DOM is loaded. Use this:

<html>
    <head>
        <script async src="..."></script>
        ...
    </head>
    <body>
        ...
        ...
        <script>(function() { init(); })();</script>
    </body>
</html>

Function init() will fire when the DOM is ready.

Also you're using setTimeout() wrong, take a look at this example .

var what_to_do = function(){ do_stuff(); };
var when_to_do = 3000; // 3000ms is 3 seconds

var timer = setTimeout(what_to_do, when_to_do);

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