简体   繁体   English

有没有办法让你的功能“冷却”?

[英]Is there a way to make a "cooldown" to your function?

im currently making a diashow or a slideshow for an website.我目前正在为网站制作 diashow 或幻灯片。 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这是diashow的一个小提琴:在此处输入链接描述

 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 *编辑我检查了小提琴,显然即使更改幻灯片也不起作用叹息

just put a delay and a 'lastClick' variable in your code.只需在您的代码中放置一个delay和一个“lastClick”变量。 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.随意编辑delay变量。

PS: The var keyword is outdated, please check out let and const . PS: var关键字已过时,请查看letconst

I am not sure if this is going to work, I am a learner to javascript as well.我不确定这是否可行,我也是 javascript 的学习者。 Suppose there is a button click function called click1() and there is a function called loadclick1() so in short this would look like假设有一个名为click1()的按钮点击函数和一个名为loadclick1()的函数,所以简而言之,这看起来像

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

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我的问题是不允许通过 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 :和 HTML 按钮:

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

So far it seems to be bullet-proof, Does anybody see a flaw ?到目前为止它似乎是防弹的,有人看到缺陷吗?

What you're thinking of is called "throttling"你在想什么叫做“节流”

This SO question has a solution for you: Simple throttle in js这个 SO 问题为您提供了一个解决方案: 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;
  };
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM