Javascript 计数器只工作一次

Javascript counter works only once

我这里有一个 jsfiddle - http://jsfiddle.net/5z2vu47a/

这是一个简单的计时器,应该更改从数组中获取的文本

定时器只工作一次。

为什么定时器不继续工作

var name_arr = ['learn', 'product', 'buying', 'selling', 'marketing', 'managing', ];
var counter = 0;

function names(){
    alert(counter);
    $('.text p').text(name_arr[counter]);
    counter++;
    alert(counter);
}

setTimeout(names, 1000);

您需要使用setInterval

setInterval(names, 1000);

names 函数中,还要检查计数器值不应超过 name_arr.length

function names(){
    alert(counter);
    $('.text p').text(name_arr[counter]);
    if(counter<(name_arr.length-1))
     counter++;
    else
     counter=0;
    alert(counter);
}

您使用了 setTimeout,它会等待 1 秒然后执行您的功能。

你想要setInterval

setTimeout 运行s 仅一次,在指定的延迟后。
如 MDN WindowTimers.setTimeout()

中所述

Calls a function or executes a code snippet after a specified delay.

setInterval 运行s 间隔,间隔指定的延迟。 如 MDN WindowTimers.setInterval()

中所述

Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. Returns an intervalID.

所以,setInterval 将永远 运行,除非你用 clearInterval 打破它。

function doStuff() {
    // Doing ome nice and fancy stuff here...
}

var interval = setInterval(doStuff, 1000);

// this will stop the interval loop
clearInterval(interval);