简体   繁体   English

使用jQuery调用onblur + onfocus函数窗口

[英]Using jQuery to recall a function window onblur+ onfocus

hI got a problem to use jQuery to recall afunction if window is on focus. 如果窗口处于焦点位置,我在使用jQuery调用功能时遇到问题。 And when window is not on focus (onblur) so pause that function until window is on focus again. 并且当窗口没有聚焦时(onblur),请暂停该功能,直到窗口再次聚焦。

Here is my code: 这是我的代码:

function functiondosomething (user_id) {

var myInterval;
var time_delay = 1000;


    $(window).focus(function () {

 setTimeout(function() { functiondosomething (user_id); }, time_delay);


    }).blur(function () {
        clearTimeout(myInterval); // Clearing interval on window blur

    });

 setTimeout(function() { functiondosomething (user_id); }, time_delay);// ## problem here

}

My problem is : 我的问题是:

  1. When I remove that line (which I marked problem here above.) the function will not work at first time until I click out of window to make it onblur and come back on focus again, so it starting to work. 当我删除该行(在上面在此处标记为问题的行)时,该功能将无法正常工作,直到我从窗口外单击以使其模糊并再次重新聚焦后,它才开始起作用。

  2. If I let that line (which I marked problem here above.) be there, the function could not pause, even I click out of window to make it be onblur. 如果我将该行(在上面在此处标记为问题)放在那儿,该功能将无法暂停,即使我单击窗口之外的按钮也可以使其模糊。

  3. When I click onfocus it start working and stop. 当我单击onfocus时,它开始工作并停止。 I have to click out of window and focus the window again again and again. 我必须单击窗口外并一次又一次地聚焦窗口。 Something like it need to be activate by clicking out of window and clicking back to window again. 需要通过单击窗口外并再次单击回到窗口来激活它。

    What should I do ? 我该怎么办 ?

I see a few problems here: 我在这里看到一些问题:

  1. You're not setting myInterval so when you call clearTimeout(myInterval) it's not clearing anything. 您没有设置myInterval所以在调用clearTimeout(myInterval)时不会清除任何内容。
  2. You're using the same function to set up your listeners and call setTimeout recursively. 您正在使用相同的函数来设置侦听器并递归调用setTimeout This means your handlers are being set every time you recur, and the recursion means it will run whether the handlers run or not. 这意味着每次递归时都将设置您的处理程序,并且递归意味着无论处理程序是否运行,它将运行。

I think you need to separate things a bit: 我认为您需要将一些内容分开:

function functiondosomething(user_id) {
  // Do stuff...
}

function setupHandlers(user_id) {
  var myInterval;
  var time_delay = 1000;

  function doSomethingWrapper() { 
    functiondosomething(user_id);
    myInterval = setTimeout(doSomethingWrapper, time_delay); 
  }

  $(window).focus(function () {
    doSomethingWrapper();
  }).blur(function () {
    clearTimeout(myInterval); // Clearing interval on window blur
  });
  doSomethingWrapper();
};

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

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