简体   繁体   中英

Killing function after specified period of time

I am running some banner ads with some pretty strict size restrictions, so I've gone with an ultra simple slideshow with Javascript and CSS. I'm trying to kill the automatic slideshow after a period of time, but can't seem to work it out.

window.addEventListener("DOMContentLoaded", function(e) {
    var stage = document.getElementById("stage");
    var fadeComplete = function(e) { stage.appendChild(arr[0]); };
    var arr = stage.getElementsByTagName("img");
    for(var i=0; i < arr.length; i++) {
        arr[i].addEventListener("animationend", fadeComplete, false);
    }
}, false);

How would I go about simply killing this function after 15 seconds so it just ceases to do anything?

Just an edit, I've added a setTimeout to the function but it doesn't seem to be working.

window.addEventListener("DOMContentLoaded", function slideshow(e) {
    var stage = document.getElementById("stage");
    var fadeComplete = function(e) { stage.appendChild(arr[0]); };
    var arr = stage.getElementsByTagName("img");
    for(var i=0; i < arr.length; i++) {
      arr[i].addEventListener("animationend", fadeComplete, false);
    }
    }, false);
    setTimeout(slideshow, 2000);

And here is another attempt at wrapping setTimeOut over the eventListener which seems to kill the script entirely at 0 seconds:

setTimeout(()=> window.addEventListener("DOMContentLoaded", function(e) {
    var stage = document.getElementById("stage");
    var fadeComplete = function(e) { stage.appendChild(arr[0]); };
    var arr = stage.getElementsByTagName("img");
    for(var i=0; i < arr.length; i++) {
      arr[i].addEventListener("animationend", fadeComplete, false);
    }
  }, false), 10000);

Wrapping a setTimeout around a window.removeEventListener(...) outta do the trick!

setTimeout(()=> window.removeEventListener(...), 1500);

Note: setTimeout executes a function, once, after waiting a specified number of milliseconds

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