版權聲明:轉載請附鏈接,就這個要求。 https://blog.csdn.net/johnstrive/article/details/42216005
通常用的方法:
啓動定時器:
window.setInterval(Method,Time)
Method是定時調用的js方法:Time是間隔時間,單位是毫秒
取消定時器:
clearInterval(Method);
那麼問題來了。用 clearInterval(timerid);來清除,往往不能馬上停止,用什麼方法比較好解決?
優化方案如下:
var timeout = false; //啓動及關閉按鈕
function time()
{
if(timeout) return;
Method();
setTimeout(time,100); //time是指本身,延時遞歸調用自己,100爲間隔調用時間,單位毫秒
}
總結
一般不用setInterval,而用setTimeout的延時遞歸來代替interval。
setInterval會產生回調堆積,特別是時間很短的時候。