Search code examples
javascriptfunctionparametersslideshow

JavaScript function parameter error


I have this simple slideshow set up and it all works fine if I remove the parameters and add the class and speed manually.

If I use parameters to set the class and speed, it fails. With the first image getting the current class applied and then the dom seems to go crazy.

‘undefined’ pops up a lot although there are no errors in console.

Any help would be appreciated. Thanks

let pos = 0;

window.addEventListener("load", function(event) {
    testIt('current', 5000);
});

function testIt(_class, _speed) {
   const testPara = document.querySelectorAll('.bg_imgs');

   let i;
   for(i = 0; i < testPara.length; i++) {
       testPara[i].classList.remove(_class);
   }

   pos++;


   if(pos > testPara.length) {pos = 1;}

   testPara[pos-1].classList.add(_class);

   setTimeout(_class, _speed); }

Solution

  • SetTimeout takes a function as its first param. If you are trying to delay the recursion try:

    setTimeout(() => testIt(_class, _speed), _speed)

    Thought window.requestAnimationFrame would be a better solution. More info on animation frame