'Is there a way to make a "cooldown" to your function?

im currently making a diashow or a slideshow for an website. And everything is set up except one thing. The user is able to spam the slideshow thus resulting in skipped animation. I want to add a cooldown to skipping the slides manually. But i couldnt figure out any solution. Help is appreciated!

Heres a fiddle of the diashow: enter link description here

var images = [
  "url(https://cdn.discordapp.com/attachments/461567193927385091/534789187560407045/picture1.png)",
  "url(https://cdn.discordapp.com/attachments/461567193927385091/534789189162762240/picture2.png)",
  "url(https://cdn.discordapp.com/attachments/461567193927385091/534789190500614147/picture3.png)",
  "url(https://cdn.discordapp.com/attachments/461567193927385091/534789199837265929/picture4.png)"
];
var num = 0;
var interval = setInterval(next, 5000);

function next() {
  var diashow = document.getElementById("diashow");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  diashow.style.backgroundImage = images[num];
}

function prev() {
  var diashow = document.getElementById("diashow");
  num--;
  if (num < 0) {
    num = images.length - 1;
  }
  diashow.style.backgroundImage = images[num];
}

function stop() {
  clearInterval(interval);
}

function set() {
  interval = setInterval(next, 5000);
}
#diashow {
  user-select: none;
  transition-duration: 1s;
  width: 600px;
  height: 224px;
  background-size: 600px 224px;
  background-position: center;
  background-image: url(https://cdn.discordapp.com/attachments/461567193927385091/534789187560407045/picture1.png);
}

#diashow div {
  width: 300px;
  height: 224px;
  background-color: transparent;
  overflow: hidden;
  cursor: pointer;
  display: inline-block;
  transition-duration: 1s;
  opacity: 0.4;
}

#divleft:hover {
  box-shadow: inset 50px 0px 0px 0px white;
}

#divright:hover {
  box-shadow: inset -50px 0px 0px 0px white;
}
<div id="diashow" onmouseover="stop()" onmouseout="set()">
  <div id="divleft" onclick="prev()"></div>
  <div id="divright" onclick="next()"></div>
</div>

*edit i checked the fiddle and apparently even the changing of the slides doesnt work sigh



Solution 1:[1]

just put a delay and a 'lastClick' variable in your code. I have tested it, it is working:

var delay = 800;
var lastClick = 0;
var images = [
    "url(https://cdn.discordapp.com/attachments/461567193927385091/534789187560407045/picture1.png)",
    "url(https://cdn.discordapp.com/attachments/461567193927385091/534789189162762240/picture2.png)",
    "url(https://cdn.discordapp.com/attachments/461567193927385091/534789190500614147/picture3.png)",
    "url(https://cdn.discordapp.com/attachments/461567193927385091/534789199837265929/picture4.png)"];
var num = 0;
var interval = setInterval(next, 5000);
function next(){
    console.log(lastClick);
    if (lastClick >= (Date.now() - delay))
        return;
    lastClick = Date.now();
    var diashow = document.getElementById("diashow");
    num++;
    if(num >= images.length){num = 0;}diashow.style.backgroundImage = images[num];}
function prev(){
    if (lastClick >= (Date.now() - delay))
        return;
    lastClick = Date.now();
    var diashow = document.getElementById("diashow");
    num--;
    if(num < 0) {num = images.length-1;}diashow.style.backgroundImage = images[num];}
function stop(){clearInterval(interval);}
function set(){interval = setInterval(next, 5000);}

Feel free to edit the delay variable.

PS: The var keyword is outdated, please check out let and const.

Solution 2:[2]

I am not sure if this is going to work, I am a learner to javascript as well. Suppose there is a button click function called click1() and there is a function called loadclick1() so in short this would look like

function loadclick1() {
    if (//button-clicked) {
        function click1() {
            //Animation code here;
            setTimeout(loadclick1(), 3000) //This will set a timeout until the function is ready
        }
    }
}

Solution 3:[3]

I was having the same idea, but for a cooldown for the function triggered by a button (to avoid spamming the server programmatically or not)

my problem was to not let the cooldown variables accessible via javascripting

i worked it around like that :

const buttonFunction = (function setup () { 
// const prevents from reassigning
  const coolDown = 5000 // 5s cooldown
  let lastClick = Date.now() - coolDown // to start fresh

  function startCoolDown () {
    lastClick = Date.now() // maybe useless function
  }
  function checkCoolDown () {
    const notOver = Date.now() - lastClick < coolDown
    if (notOver) alert('stop spamming the server !')
    // using an alert it will block javascript loops
    return !notOver
  }

  return function (arguments) {
    if (checkCoolDown()) {
      startCoolDown()

      // do your stuff with arguments here
    }
  }
})() // all variables are safely nested !

and the HTML button :

<button onclick="buttonFunction('argument')">
  button
</button>

So far it seems to be bullet-proof, Does anybody see a flaw ?

Solution 4:[4]

You could use lodash library and it's throttle() function, much quicker and cleaner.

Solution 5:[5]

What you're thinking of is called "throttling"

This SO question has a solution for you: Simple throttle in js

Shameless copy paste of the above:

// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
function throttle(func, wait, options) {
  var context, args, result;
  var timeout = null;
  var previous = 0;
  if (!options) options = {};
  var later = function() {
    previous = options.leading === false ? 0 : Date.now();
    timeout = null;
    result = func.apply(context, args);
    if (!timeout) context = args = null;
  };
  return function() {
    var now = Date.now();
    if (!previous && options.leading === false) previous = now;
    var remaining = wait - (now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      previous = now;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining);
    }
    return result;
  };
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lukas Germerott
Solution 2 Stuntman 82
Solution 3
Solution 4 michalstruck
Solution 5