gpt4 book ai didi

javascript - 为什么这个 JS 变量在页面加载时运行

转载 作者:行者123 更新时间:2023-12-02 19:09:38 27 4
gpt4 key购买 nike

我不明白为什么 MC.caro.myTimer() 在页面加载时运行,它是一个变量。那么如果我不调用它,它是如何运行的呢?

我认为这可能与我的自动执行功能有关?

    var MC = {};

(function($){
"use strict";

MC.init = function (){
//disable to turn off carousel
MC.caro.init();
};

MC.caro = {
init: function(){
//Build carousel for us to use
MC.caro.build();
//Bind click events to buttons
$('.mc-carousel--nav--buttons').on('click','li',function(){
MC.caro.advance($(this));

//stop the current ticking
MC.caro.stopMyTimer();

//Start up movement after 15seconds
setInterval(function(){MC.caro.myTimer()},10000);
console.info('running');
});
},
build: function(){
MC.caro.jsonRun(function(){
console.info('running1');
});
},
myTimer: function(){
console.info('running2');
MC.caro.advance(nextItem,'slow');
},
//Sets up the timer
timer:setInterval(function(){MC.caro.myTimer()},5000),
stopMyTimer: function(){
clearInterval(MC.caro.timer);
}
}
})(jQuery);

MC.init();

还有一个问题:

当我点击 $('.mc-carousel--nav--buttons').on('click','li',function(){ 时,代码将等待 15 秒然后运行。正如预期的那样。但是如果我非常快地单击它 5 次,它将等待 15 秒,然后以与我单击完全相同的时间和顺序运行,这意味着 MC.caro.stopMyTimer(); 是在我的点击事件中调用的方法不起作用。

此外,这不是完整的代码,我也无法将其放入 fiddle 中,因为它对内部网有很大的依赖性。

所以应用程序您看不到有效的示例。

最佳答案

您将其设置为 setInterval 的返回值

timer: setInterval(function(){MC.caro.myTimer()},5000),

立即评估。

关于javascript - 为什么这个 JS 变量在页面加载时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13914088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com