efe*_*nza 4 javascript jquery setinterval onready
编辑:我所说的多次触发的意思是 newjob() 将每 5 秒触发 3 次...所以在 20 秒内我将触发它 12 次,而不是我想要的 4 次。所以它每 5 秒触发多次,而不是每 5 秒触发一次。
我有一个使用 Toastr 创建的函数,用于在我的 Web 应用程序上显示消息。我最终会将其与 API 的 ajax 请求联系起来,以确定是否显示消息,但现在我只是测试它的外观。
我正在设置一个间隔,但它会多次触发其中的函数(通常为 3 次)。
$(document).ready(function() {
setInterval(function () {
newJob();
}, 5000);
});
Run Code Online (Sandbox Code Playgroud)
我无法执行 setInterval( function(e) { } 因为 e 未定义,因为没有与之关联的事件,点击时,我使用了 e.stopImmediatePropagation(); 让它只触发一次。我怎样才能如果我没有 e,则按设定的时间间隔停止立即传播?
谢谢。
编辑:完整代码:
var newJob = function(e) {
var i = -1;
var $toastlast;
var getMessage = function () {
var msgs = ["There's a new job in the job dispatch queue", "A job pending approval has timed out"];
i++;
if (i === msgs.length) {
i = 0;
}
return msgs[i];
};
var shortCutFunction = "success"; // 'success' or 'error'
toastr.options = {
closeButton: true,
progressBar: true,
debug: false,
positionClass: 'toast-top-full-width',
onclick: null,
timeOut: "0",
extendedTimeOut: "0",
showDuration: "0",
hideDuration: "0",
showEasing: "swing",
hideEasing: "linear",
showMethod: "fadeIn",
hideMethod: "fadeOut",
};
toastr.options.onclick = function () {
window.location.href = "/dispatcher";
};
var msg = getMessage();
$("#toastrOptions").text("Command: toastr["
+ shortCutFunction
+ "](\""
+ msg
+ "\")\n\ntoastr.options = "
+ JSON.stringify(toastr.options, null, 2)
);
var $toast = toastr[shortCutFunction](msg);
};
$(document).ready(function() {
setInterval(function () {
console.log('set interval');
newJob();
}, 5000);
});
Run Code Online (Sandbox Code Playgroud)
这是我的index.phtml 文件:
<?php
echo $this->headScript()->appendFile($this->basePath() . '/plugins/toastr/toastr.js')
echo $this->headScript()->appendFile($this->basePath().'/js/dispatchernotification.js');
?>
Run Code Online (Sandbox Code Playgroud)
我所做的就是将我想要运行的 JavaScript 添加到我的 index.phtml 文件和 toastr 库中。通过 console.logging 在间隔内,我得到三个日志。
这是一个小提琴..不知道如何运行它,因为它已经准备好了 http://jsfiddle.net/efecarranza/rfvbhr1o/
确保将您的放在setInterval
之外$(document).ready(function() {...})
。所以它会是这样的:
<script>
$(document).ready(function() {
... some code ...
});
var myInterval;
clearInterval(myInterval);
myInterval = setInterval(function() {
... your code is here ...
}, 5000);
</script>
Run Code Online (Sandbox Code Playgroud)
由于某种原因,如果每次$(document).ready()
您再次动态地打开同一页面时,它都会双重设置setInterval
进程,并且clearInterval
在您实际刷新浏览器之前该功能没有帮助。
归档时间: |
|
查看次数: |
16414 次 |
最近记录: |