如果在一段时间后没有再次运行,则只运行JavaScript函数 [英] Only run a JavaScript function if it is not run again after a set amount of time

查看:48
本文介绍了如果在一段时间后没有再次运行,则只运行JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入控制元素的状态变化非常快。这会导致元素闪烁,因为它的一部分会发生变化。

I have an input which controls the state of an element changing very rapidly. This causes that element to flicker as parts of it change.

我正在尝试存储这些状态更改,然后在设定的时间内(任意500毫秒)更改状态时不提供任何更改。

I am trying to store these state changes and then providing nothing has changed for a set amount of time (an arbitrary 500ms) change the state.

我试图使用超时解决这个问题,如下面的代码所示(与小提琴中的代码相同。):

I have tried to solve this using timeouts as demonstrated in the code below (the same code as in the fiddle.):

var changingToHappy = false;

// Original no attempts to fix functions.
//var ifHappy = function () {
//  $("#face").text(':)');
//};
//
//var ifNotHappy = function () {
//  $("#face").text(':(');
//};

var ifHappy = function () {
  changingToHappy = true;
  setTimeout(function () {
    if (changingToHappy) {
      $("#face").text(':)');
    }
  }, 500);
};

var ifNotHappy = function () {
  changingToHappy = false;
  setTimeout(function () {
    if (!changingToHappy) {
      $("#face").text(':(');
    }
  }, 500);
};

$("#textBox").keypress(
  function (event) {
    if (event.which == 49) {
      ifHappy();
      $("#flickerFace").text(':)');
    }
    if (event.which == 50) {
      ifNotHappy();
      $("#flickerFace").text(':(');
    }
  }
);

如果您在小提琴中快速按1,2,1,2等等,脸部将暂时不会闪烁,然后是超时会赶上并且会开始改变状态。

If you rapidly press 1, 2, 1, 2 and so on in the fiddle the face will remain not flickery for a moment and then the timeouts will catchup and it will begin to change state.

这个小提琴 http://jsfiddle.net/9w70wxgz/4/ 模拟了这个问题。

This fiddle http://jsfiddle.net/9w70wxgz/4/ simulates the problem.

澄清一下如果没有尝试,我只想改变面部在一段时间内改变其状态。

To clarify I only want the face to change if nothing has tried to change its state for a set amount of time.

推荐答案

你在寻找什么被称为去抖动函数,下面是一段代码示例(你几乎就在那里):

What you're looking for is called a debounced function, here is an example with a piece of your code (you're almost there):

//storage for timer
var notHappyTimer;

var ifNotHappy = function () {
  changingToHappy = false;

  //removes timer if event fires in less than 500ms
  clearTimeout(notHappyTimer);

  //resets it to attempt again in 500ms
  notHappyTimer = setTimeout(function () {
    if (!changingToHappy) {
      $("#face").text(':(');
    }
  }, 500);

};

正如您所看到的,您只需将超时分配给一个变量,该变量每次触发该函数时都会自行清除,然后再次启动计时器。这样可以确保仅在该函数尚未在500ms内触发。

As you can see, you just assign the timeout to a variable that clears itself every time the function is fired, then starts the timer again. This ensures that the text change only happens if the function hasn't been fired in 500ms.

这篇关于如果在一段时间后没有再次运行,则只运行JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆