简体   繁体   中英

setTimeout doesn't seem to work in Chrome

This setTimeout works perfectly in Firefox, but in Chrome nothing in function timeoutTrigger ever happens, including the alert. Any ideas?

var $this = $('.active-more');

function timeoutTrigger() {
    $this.closest(".container").nextAll(".container:first").find(".description:first").removeClass('hide');
    $this.closest(".container").nextAll(".container:first").find(".back:first").find("img.portfolio").remove();
    alert("is this thing on?");
}

setTimeout(function(){timeoutTrigger()},400)

Switch your setTimeout statement to the following: setTimeout(timeoutTrigger,400); The one you wrote is for when the function you're calling has a parameter. Also, you're missing a semicolon.

Google has changed the Content Security Policy which impacts using setTimeout() in some browsers. Please read: https://developer.chrome.com/extensions/contentSecurityPolicy

We had trouble with settimeout function on Chrome. We wanted to run a API check in every 10 seconds to update page content if there is change in data. But although we set settimeout function to run in every 10 seconds, Chrome does not run it correctly if browser is inactive. (While Safari runs the code correctly even if it is inactive).

Our experiment shows that Chrome runs our function about minutely or a little longer when it is inactive. So checking updates minutely does not broke our code.

But we had second function which runs every minutes and changes content locally every minutes. To be specific, we change waiting times and play times of games which we are showing in the page content. So as we can not depend on Chrome to run at exact minutes, our solution is to save when the code is run last time, and check the minutes passed between dates, and change the waiting times and playing times accordingly.

 var $last_run_time; 
 var $interval = 10000; // 10 seconds

 $current_date = new Date();
 $last_run_time = $current_date;
 console.log('Timeout started '+ $current_date.toLocaleTimeString());
 setTimeout(my_refresh_function, $interval));

function my_refresh_function() {
        setTimeout(my_refresh_function, $interval);
        $current_date = new Date();
        console.log('Refresh run: '+ $current_date.toLocaleTimeString());
        $minutes_passed = Math.floor((Math.abs($current_date - $last_run_time)/1000)/60);

  if ($minutes_passed > 0 ) {
       // Make the changes you want for passed minutes
       // for example increase play time $play_time += $minutes_passed
       // and reduce waiting times $waiting_time -= $minutes_passed
        console.log('Minutes updated +- '+ $minutes_passed + ' mins, at: ' + $current_date.toLocaleTimeString());

  }
 }

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