How to stop function on blur()

不问归期 提交于 2020-01-16 01:20:27

问题


myfucntion = send request after 5 sec

document.ready(myfucntion)
$(window).focus(myfucntion)
$(window).blur(stop(myfucntion))

is this possible to stop a function on blur called previously in document.ready


回答1:


Have a global timer:

var intervalId;

And it would be better to have two functions:

startfunction() {
  intervalId = setTimeout(function () {
    // send request after 5 seconds
  }, 5000);
}
stopfunction() {
  clearTimeout(intervalId);
}

And use them like this:

$(document).ready(startfunction);
$(document).ready(function () {
  $(window).focus(startfunction);
  $(window).blur(stopfunction);
});



回答2:


Here is an example of how to make what you want work

var timer; // make it global so it can be accessed inside functions

var myFunction = function () {
  timer = setTimeout(function() {
    //do something after 5 seconds
  }, 5000);
}

var stopMyFunction = function () {
  clearTimeout(timer);
}

$(document).ready(myFunction)
$(window).focus(myFunction)
$(window).blur(stopMyFunction))


来源:https://stackoverflow.com/questions/34548020/how-to-stop-function-on-blur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!