実行タイミングはわしが決めた。
javascriptにはミリ秒を使って実行タイミングをズラす手法が存在しています。
それについてやっていきましょう。
setTimeout(【処理】,ミリ秒)
指定ミリ秒後に1度だけ【処理】を実行します。
戻り値はsetTimeoutオブジェクトとなります。
document.getElementById('test').onclick = function() { // とある要素をクリック時、1秒後にルートディレクトリへ遷移します。 setTimeout(fucntion() { window.location = '/' },1000); }
clearTimeout(【timeoutオブジェクト】);
指定されたsetTimeoutのタイマーを止めます。
alertタイマー開始
alertタイマー停止
window.onload = function() { var timeoutobj = ""; document.getElementById('test').onclick = function() { // とある要素をクリック時、1秒後にルートディレクトリへ遷移します。 timeoutobj = setTimeout(fucntion() { alert('3秒たった'); },3000); } document.getElementById('test2').onclick = function() { if(timeoutobj == "" || timeoutobj == undefuned) retun false; clearTimeout(timeoutobj); } }
setInterval(【処理】,ミリ秒)
指定ミリ秒経過ごとに【処理を実行します。】
戻り値はsetInervalオブジェクトとなります。
document.getElementById('test3').onclick = function() { // とある要素をクリック時、5秒ごとにアラートを表示させます。 setInterval(fucntion() { alert('5秒経過'); },5000); }
clearInterval(【intervalオブジェクト】);
指定されたsetIntervalのタイマーを止めます。
consoleインターバル処理開始
consoleインターバル処理停止
window.onload = function() { var intervalobj = ""; document.getElementById('test3').onclick = function() { // とある要素をクリック時、1秒後にルートディレクトリへ遷移します。 // 連打制御入れてないから連打すんな intervalobj = setInterval(function() { console.log('1秒経過'); },1000); } document.getElementById('test4').onclick = function() { if(intervalobj == "" || intervalobj == undefined) return false; clearInterval(intervalobj); } }
特に多用せず、だけどすごく使える子です。
制御にも使えますが、そのお話はまた今度で。