How do I stop and start setInterval?
setInterval
Suppose I have a textarea. I want to stop setInterval on focus and restart setInterval on blur (with jQuery).
textarea
你必须在启动时存储这个时间间隔的 定时器,稍后你将使用这个值来停止它,使用 clearInterval函数:
clearInterval
$(function () { var timerId = 0; $('textarea').focus(function () { timerId = setInterval(function () { // interval function body }, 1000); }); $('textarea').blur(function () { clearInterval(timerId); }); });
将 setInterval的返回值存储在一个变量中,然后使用它来清除间隔。
var timer = null; $("textarea").blur(function(){ timer = window.setInterval(function(){ ... whatever ... }, 2000); }).focus(function(){ if(timer){ window.clearInterval(timer); timer = null } });
SetInterval 返回一个 id,您可以使用它来取消 clearInterval ()的间隔
This is based on CMS's answer. The question asked for the timer to be restarted on the blur and stopped on the focus, so I moved it around a little:
$(function () { var timerId = 0; $('textarea').focus(function () { clearInterval(timerId); }); $('textarea').blur(function () { timerId = setInterval(function () { //some code here }, 1000); }); });